diff --git a/eng/CodeAnalysis.src.globalconfig b/eng/CodeAnalysis.src.globalconfig index 831a1b9cfb4ca5..e9963da315acd9 100644 --- a/eng/CodeAnalysis.src.globalconfig +++ b/eng/CodeAnalysis.src.globalconfig @@ -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 diff --git a/eng/CodeAnalysis.test.globalconfig b/eng/CodeAnalysis.test.globalconfig index 0b5cef6baa982a..eff7ffaf9ccfe8 100644 --- a/eng/CodeAnalysis.test.globalconfig +++ b/eng/CodeAnalysis.test.globalconfig @@ -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 diff --git a/src/coreclr/System.Private.CoreLib/src/Microsoft/Win32/OAVariantLib.cs b/src/coreclr/System.Private.CoreLib/src/Microsoft/Win32/OAVariantLib.cs index 958199de5a5d44..ea62d5e2fbd69a 100644 --- a/src/coreclr/System.Private.CoreLib/src/Microsoft/Win32/OAVariantLib.cs +++ b/src/coreclr/System.Private.CoreLib/src/Microsoft/Win32/OAVariantLib.cs @@ -72,8 +72,11 @@ internal static class OAVariantLib * 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, diff --git a/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs index c84e918d843035..612697a96cf2fc 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs @@ -448,8 +448,11 @@ public static Attribute[] GetCustomAttributes(MemberInfo element, Type attribute 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 @@ public static Attribute[] GetCustomAttributes(MemberInfo element) 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 @@ public static bool IsDefined(MemberInfo element, Type attributeType) 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 @@ public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attrib 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 @@ public static Attribute[] GetCustomAttributes(ParameterInfo element!!, Type attr 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 @@ public static bool IsDefined(ParameterInfo element, Type attributeType) 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 @@ public static Attribute[] GetCustomAttributes(Module element) 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 @@ public static bool IsDefined(Module element, Type attributeType) 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 @@ public static Attribute[] GetCustomAttributes(Assembly element, Type attributeTy 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 @@ public static Attribute[] GetCustomAttributes(Assembly element) 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 @@ public static bool IsDefined(Assembly element, Type attributeType) 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)) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs index 894f68eae41713..aac36f4f69123c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs @@ -33,8 +33,10 @@ IEnumerator IEnumerable.GetEnumerator() // 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 @@ public void CopyTo(Array array!!, int index) // 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 @@ public bool Contains(object key) 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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs index 3afbff9eb08000..0bf04439f20b5b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs @@ -34,8 +34,11 @@ public abstract partial class Delegate : ICloneable, ISerializable // 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 @@ protected Delegate(object target!!, string method!!) // 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 @@ protected virtual MethodInfo GetMethodImpl() // 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 @@ protected virtual MethodInfo GetMethodImpl() } // 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 @@ protected virtual MethodInfo GetMethodImpl() } // 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 @@ protected virtual MethodInfo GetMethodImpl() // 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 @@ protected virtual MethodInfo GetMethodImpl() // // 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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs index 4f2fbd89bc29bb..382b5cc4d340e4 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/GC.CoreCLR.cs @@ -302,8 +302,10 @@ public static void WaitForPendingFinalizers() [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 @@ public static void SuppressFinalize(object obj!!) [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 @@ internal static void RegisterMemoryLoadChangeNotification(float lowMemoryPercent } } - 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) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs index 8f71f7112ef0d9..970684d6330db9 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs @@ -23,8 +23,10 @@ public static Assembly Load(string assemblyString) [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 @@ public static Assembly Load(string assemblyString) // 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs index eadae5efbab2aa..f5b41bddcea07c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -36,12 +36,14 @@ public sealed partial class AssemblyBuilder : Assembly #region Constructor - internal AssemblyBuilder(AssemblyName name!!, + internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, Assembly? callingAssembly, AssemblyLoadContext? assemblyLoadContext, IEnumerable? 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 @@ public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? vers /// /// 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); + lock (SyncRoot) { TypeBuilder.DefineCustomAttribute( @@ -289,8 +294,10 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) /// /// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder. /// - public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { + ArgumentNullException.ThrowIfNull(customBuilder); + lock (SyncRoot) { customBuilder.CreateCustomAttribute(_manifestModuleBuilder, AssemblyDefToken); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs index f910b8a7e7da0d..d8a31cf407396c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs @@ -48,8 +48,15 @@ public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, Fi // 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"); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs index d5d36a60b4231f..0828c9f2cc5455 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -32,8 +32,10 @@ internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) // *** 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 @@ public override LocalBuilder DeclareLocal(Type localType!!, bool pinned) // 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 @@ public override void Emit(OpCode opcode, MethodInfo meth!!) 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 @@ public override void Emit(OpCode opcode, ConstructorInfo con!!) 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 @@ public override void Emit(OpCode opcode, Type type!!) 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 @@ public override void Emit(OpCode opcode, FieldInfo field!!) 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 @@ public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallCon 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 @@ public override void EmitCall(OpCode opcode, MethodInfo methodInfo!!, Type[]? op 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); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs index 0942a3a0312002..24641e490a1ada 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -89,8 +89,10 @@ public DynamicMethod(string name, 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 @@ public DynamicMethod(string name, 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 @@ public DynamicMethod(string name, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, - Module m!!, + Module m, bool skipVisibility) { + ArgumentNullException.ThrowIfNull(m); + Init(name, attributes, callingConvention, @@ -144,8 +150,10 @@ public DynamicMethod(string name, 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 @@ public DynamicMethod(string name, 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 @@ public DynamicMethod(string name, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, - Type owner!!, + Type owner, bool skipVisibility) { + ArgumentNullException.ThrowIfNull(owner); + Init(name, attributes, callingConvention, @@ -246,7 +258,7 @@ private static RuntimeModule GetDynamicMethodsModule() [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 @@ private void Init(string name!!, bool skipVisibility, bool transparentMethod) { + ArgumentNullException.ThrowIfNull(name); + CheckConsistency(attributes, callingConvention); // check and store the signature @@ -759,8 +773,10 @@ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? bind 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 @@ public override object[] GetCustomAttributes(bool inherit) 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; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs index c393d8dd1d6857..c28109acf2d124 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs @@ -46,8 +46,10 @@ internal int GetEventToken() 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 @@ public void AddOtherMethod(MethodBuilder mdBuilder) // 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 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) } // 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs index 5c65ff31c00b67..a5c2723524a67d 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs @@ -154,8 +154,11 @@ public void SetConstant(object? defaultValue) 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 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) 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; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs index 65d97cd384e7d3..26c1ae27f88ad8 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs @@ -474,8 +474,10 @@ public virtual void Emit(OpCode opcode, int arg) 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 @@ public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv 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 @@ public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo!!, Type[]? opt 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 @@ public virtual void Emit(OpCode opcode, SignatureHelper signature!!) 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 @@ public virtual void Emit(OpCode opcode, Label label) } } - 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 @@ public virtual void Emit(OpCode opcode, string str) 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 @@ public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccess { // 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 @@ public virtual void EmitWriteLine(LocalBuilder localBuilder) 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. diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs index 94f91439aa33af..47be41675c14ee 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs @@ -130,8 +130,10 @@ internal MethodBuilder(string name, MethodAttributes attributes, CallingConventi #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 @@ public override MethodInfo MakeGenericMethod(params Type[] typeArguments) 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 @@ internal Module GetModule() 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 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) ParseCA(con); } - public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) + public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { + ArgumentNullException.ThrowIfNull(customBuilder); + ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataToken); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs index 2c8f6173210159..eee44ef3e7e80f 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -222,8 +222,10 @@ private int GetTypeRefNested(Type type, Module? refedModule) 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 @@ internal int GetTypeToken(Type type) 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 @@ internal int GetMethodToken(MethodInfo method) // 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 @@ internal int GetFieldToken(FieldInfo field) } } - private int GetFieldTokenNoLock(FieldInfo field!!) + private int GetFieldTokenNoLock(FieldInfo field) { + ArgumentNullException.ThrowIfNull(field); + int tr; int mr; @@ -1292,16 +1300,20 @@ private int GetFieldTokenNoLock(FieldInfo field!!) 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 @@ internal int GetSignatureToken(SignatureHelper sigHelper!!) 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 @@ internal int GetSignatureToken(byte[] sigBytes!!, int sigLength) #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 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) 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 } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs index 6be9a88cfe9210..3eef9c642eb866 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs @@ -18,8 +18,11 @@ public virtual void SetConstant(object? defaultValue) } // 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 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) } // 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs index cb619bde1353da..323b6dd4c9371d 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs @@ -66,8 +66,10 @@ public void SetConstant(object? defaultValue) 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 @@ public void AddOtherMethod(MethodBuilder mdBuilder) // 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 @@ public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) } // 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index cacb7ac0121c55..17362b35122912 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -167,8 +167,11 @@ public static SignatureHelper GetPropertySigHelper(Module? mod, CallingConventio 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 @@ public void AddArgument(Type clsArgument) 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs index 735956362086dd..f6a1dfb3bff5e5 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs @@ -224,8 +224,10 @@ internal SymbolType(TypeKind typeKind) #endregion #region Internal Members - internal void SetElementType(Type baseType!!) + internal void SetElementType(Type baseType) { + ArgumentNullException.ThrowIfNull(baseType); + m_baseType = baseType; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs index 3fe92a5f6f7284..d2e84804adbe67 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs @@ -25,14 +25,19 @@ private sealed class CustAttr 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 @@ internal void SetInterfaces(params Type[]? interfaces) } } - 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 @@ public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInf } } - 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 @@ public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttribu } } - 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 @@ public void SetParent([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes } } - 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 @@ internal int TypeToken } } - 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs index fe79a0e8e7c83f..7b4a21e157cd64 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs @@ -7,8 +7,10 @@ public abstract partial class MemberInfo { internal virtual bool CacheEquals(object? o) { throw new NotImplementedException(); } - internal bool HasSameMetadataDefinitionAsCore(MemberInfo other!!) where TOther : MemberInfo + internal bool HasSameMetadataDefinitionAsCore(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; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs index a5b243ae8d6635..bae43fd0e9147d 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs @@ -28,8 +28,10 @@ public static partial class AssemblyExtensions /// The caller is responsible for keeping the assembly object alive while accessing the metadata blob. /// [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; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index af78adf38bcc2a..ede72347af6fbc 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -191,9 +191,11 @@ private static partial void GetType(QCallAssembly assembly, [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 @@ public override object[] GetCustomAttributes(bool inherit) 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 @@ public override Assembly GetSatelliteAssembly(CultureInfo culture) } // 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)!; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs index 35e14b8ebfee40..5b6efa638e9b2a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.CoreCLR.cs @@ -147,16 +147,20 @@ public override object[] GetCustomAttributes(bool inherit) 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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs index d28edee2403814..002d39ae38e27b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs @@ -676,8 +676,10 @@ private static extern void ParseAttributeArguments( 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 @@ internal readonly struct CustomAttributeNamedParameter 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; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs index b0d5805804208c..366c9288662bbf 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs @@ -76,16 +76,20 @@ public override object[] GetCustomAttributes(bool inherit) 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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs index d2ddb1f36091c1..cf06b03d661a96 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs @@ -61,16 +61,20 @@ public override object[] GetCustomAttributes(bool inherit) 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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs index 8cd33129735fde..c80aa9af08a766 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.CoreCLR.cs @@ -215,16 +215,20 @@ public override object[] GetCustomAttributes(bool inherit) 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 @@ public override Delegate CreateDelegate(Type delegateType, object? target) 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 @@ private Delegate CreateDelegateInternal(Type delegateType!!, object? firstArgume #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) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs index d0a74a2fc84e8b..8512a968b6c725 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs @@ -385,16 +385,20 @@ public override object[] GetCustomAttributes(bool inherit) 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 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont [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 @@ public override FieldInfo[] GetFields(BindingFlags bindingFlags) } [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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs index f889133b531f90..b0288737920cea 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs @@ -507,8 +507,10 @@ public override object[] GetCustomAttributes(bool inherit) 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 @@ public override object[] GetCustomAttributes(Type attributeType!!, bool inherit) 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; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs index 1b6c630470c3a1..d61c14b55d28c7 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs @@ -137,16 +137,20 @@ public override object[] GetCustomAttributes(bool inherit) 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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs index b3e7c67442eaf3..50d292e10dfcd8 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs @@ -10,8 +10,10 @@ internal sealed class TypeDependencyAttribute : Attribute { private readonly string typeName; - public TypeDependencyAttribute(string typeName!!) + public TypeDependencyAttribute(string typeName) { + ArgumentNullException.ThrowIfNull(typeName); + this.typeName = typeName; } } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs index 28558fb5d1dbe7..eac834cf741d09 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs @@ -94,8 +94,10 @@ public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfa /// /// If is null, the global instance (if registered) will be used. /// - 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 @@ public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, Create /// /// If the instance already has an associated external object a will be thrown. /// - 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 @@ internal static void CallReleaseObjects(ComWrappers? comWrappersImpl, IEnumerabl /// Scenarios where this global instance may be used are: /// * Object tracking via the and flags. /// - 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 @@ public static void RegisterForTrackerSupport(ComWrappers instance!!) /// * COM activation /// [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); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs index 6a93d2b5ebd84c..4f1e28e9076a7c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs @@ -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; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs index eef801c7fe4fb5..354e4b66545b84 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs @@ -32,8 +32,10 @@ public int GetNativeDataSize() return -1; } - public IntPtr MarshalManagedToNative(object ManagedObj!!) + public IntPtr MarshalManagedToNative(object ManagedObj) { + ArgumentNullException.ThrowIfNull(ManagedObj); + return Marshal.GetComInterfaceForObject(ManagedObj); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs index f360e169c496fd..c6e31e1d053e5a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs @@ -33,8 +33,10 @@ public int GetNativeDataSize() return -1; } - public IntPtr MarshalManagedToNative(object ManagedObj!!) + public IntPtr MarshalManagedToNative(object ManagedObj) { + ArgumentNullException.ThrowIfNull(ManagedObj); + if (ManagedObj is EnumeratorViewOfEnumVariant view) { return Marshal.GetComInterfaceForObject(view.GetUnderlyingObject()); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs index f96ec9367c1d91..3837e5c7f1efb9 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs @@ -30,8 +30,10 @@ public static partial class Marshal [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 @@ private static void PrelinkCore(MethodInfo m) /// 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. /// - 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 @@ public static IntPtr GetHINSTANCE(Module m!!) /// Given a managed object that wraps an ITypeInfo, return its name. /// [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 @@ public static string GetTypeInfoName(ITypeInfo typeInfo!!) /// where the RCW was first seen. Will return null otherwise. /// [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 @@ public static string GetTypeInfoName(ITypeInfo typeInfo!!) /// Return the IDispatch* for an Object. /// [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 @@ public static string GetTypeInfoName(ITypeInfo typeInfo!!) /// [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 @@ public static string GetTypeInfoName(ITypeInfo typeInfo!!) /// [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 @@ public static IntPtr CreateAggregatedObject(IntPtr pOuter, T o) where T : not /// /// Checks if the object is classic COM component. /// - public static bool IsComObject(object o!!) + public static bool IsComObject(object o) { + ArgumentNullException.ThrowIfNull(o); + return o is __ComObject; } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs index 735f788dd3ffa6..a5dedc6044b38a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs @@ -140,8 +140,10 @@ private static IntPtr ResolveUnmanagedDllUsingEvent(string unmanagedDllName, Ass 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. diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 0670e4660a8eb7..ed4c5630b1e051 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -1734,9 +1734,11 @@ internal FieldInfo GetField(RuntimeFieldHandleInternal field) #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 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn [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 candidates = GetPropertyCandidates(name, bindingAttr, types, false); if (candidates.Count == 0) @@ -2858,8 +2862,10 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn } [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 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn } [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 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn "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 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn } [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 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn } [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 methods = default; ListBuilder constructors = default; ListBuilder properties = default; @@ -3064,8 +3078,10 @@ public override MemberInfo[] GetMember(string name!!, MemberTypes type, BindingF 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 @@ public override MethodBase? DeclaringMethod #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 @@ public override Type[] GetGenericArguments() } [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)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/String.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/String.CoreCLR.cs index abf1c828fdff87..befcb1bb19d3dc 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/String.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/String.CoreCLR.cs @@ -23,13 +23,17 @@ public partial class String [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(); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs index c84f615d219a0f..c3257f9fc10df1 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/Monitor.CoreCLR.cs @@ -125,8 +125,10 @@ public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTa [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 @@ public static bool Wait(object obj, int millisecondsTimeout) [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 @@ public static void Pulse(object obj!!) [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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/Overlapped.cs index d65e4df83a75d7..1df85398ff5399 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -221,14 +221,18 @@ public IntPtr EventHandleIntPtr * 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); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.Windows.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.Windows.cs index 02dfefc1bfdbbe..66b91d05c38d36 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.Windows.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.Windows.cs @@ -47,8 +47,10 @@ public static bool BindHandle(IntPtr osHandle) } [SupportedOSPlatform("windows")] - public static bool BindHandle(SafeHandle osHandle!!) + public static bool BindHandle(SafeHandle osHandle) { + ArgumentNullException.ThrowIfNull(osHandle); + bool mustReleaseSafeHandle = false; try { diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs index 4aff36ffad43de..0906b97c6f5f35 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs @@ -392,13 +392,16 @@ public static long CompletedWorkItemCount 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), diff --git a/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs b/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs index 318487d2ef4205..2b97534fe90103 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs @@ -56,13 +56,15 @@ internal sealed partial class TypeNameParser : IDisposable #region Static Members [RequiresUnreferencedCode("The type might be removed")] internal static Type? GetType( - string typeName!!, + string typeName, Func? assemblyResolver, Func? typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { + ArgumentNullException.ThrowIfNull(typeName); + if (typeName.Length > 0 && typeName[0] == '\0') throw new ArgumentException(SR.Format_StringZeroLength); diff --git a/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs b/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs index 2a5f10d009ec91..45d5bb2a694a54 100644 --- a/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs +++ b/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs @@ -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 diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs index 1fe4e47fff9f76..d7b251ca21c24a 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs @@ -17,8 +17,10 @@ internal class SafeCertContextHandle : SafeCrypt32Handle public SafeCertContextHandle() { } - public SafeCertContextHandle(SafeCertContextHandle parent!!) + public SafeCertContextHandle(SafeCertContextHandle parent) { + ArgumentNullException.ThrowIfNull(parent); + Debug.Assert(!parent.IsInvalid); Debug.Assert(!parent.IsClosed); diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs index d563de42b80d21..63d6e61545afcb 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -42,8 +42,13 @@ public CodeTypeReference() 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(); diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs index 6508e0163da334..5ab4ff597adbe3 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs @@ -39,16 +39,26 @@ public CodeTypeReference this[int index] 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++) { diff --git a/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs b/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs index ab3a0ec42243ed..2049ff60f36aad 100644 --- a/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs +++ b/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs @@ -33,8 +33,17 @@ public static void Registration_TypeExportConventionOverridden(Type type) } } - 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 @@ public static void Registration_MemberExportConventionOverridden(Type type!!, Me } } - 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 @@ public static void Registration_MemberImportConventionOverridden(Type type!!, Me } } - 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 @@ public static void Registration_OnSatisfiedImportNotificationOverridden(Type typ } } - 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 @@ public static void Registration_PartCreationConventionOverridden(Type type!!) } } - 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 @@ public static void Registration_MemberImportConventionMatchedTwice(Type type!!, } } - 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 @@ public static void Registration_PartMetadataConventionOverridden(Type type!!) } } - 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, diff --git a/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs b/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs index 705e07a75fe38c..5e2ecc2cf50b58 100644 --- a/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs +++ b/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs @@ -188,8 +188,13 @@ protected override void Dispose(bool disposing) } #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); diff --git a/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs b/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs index 1db9e6b48a5215..835048efb1626f 100644 --- a/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs +++ b/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs @@ -7,8 +7,13 @@ namespace System.IO internal static partial class StreamHelpers { /// Validate the arguments to CopyTo, as would Stream.CopyTo. - 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); diff --git a/src/libraries/Common/src/System/IO/StringParser.cs b/src/libraries/Common/src/System/IO/StringParser.cs index 317ca98026f1fe..941e78ac52239b 100644 --- a/src/libraries/Common/src/System/IO/StringParser.cs +++ b/src/libraries/Common/src/System/IO/StringParser.cs @@ -30,8 +30,10 @@ internal struct StringParser /// The string to parse. /// The separator character used to separate subcomponents of . /// true if empty subcomponents should be skipped; false to treat them as valid entries. Defaults to false. - 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; diff --git a/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs b/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs index 1b0bec17b7273b..03ad51851843c4 100644 --- a/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs +++ b/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs @@ -149,8 +149,10 @@ internal static void ValidateArraySegment(ArraySegment arraySegment, strin } } - 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)); diff --git a/src/libraries/Common/src/System/Resources/ResourceWriter.cs b/src/libraries/Common/src/System/Resources/ResourceWriter.cs index 999dc16f55abe9..01768ac03b45d4 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -43,11 +43,16 @@ public sealed partial class 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(FastResourceComparer.Default); _caseInsensitiveDups = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -55,13 +60,20 @@ public sealed partial class 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(FastResourceComparer.Default); @@ -71,10 +83,17 @@ public sealed partial class // 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 @@ public void AddResource(string name!!, string? value) // 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 @@ public void AddResource(string name!!, object? value) // 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 @@ private void AddResourceInternal(string name, Stream? value, bool closeAfterWrit // 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); diff --git a/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs b/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs index 07ac28e32f5bb5..3a8d1fcd325f9d 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Asn1/AttributeAsn.manual.cs @@ -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(attribute.RawData) }; } diff --git a/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs b/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs index 4e6b9372bb1417..53f57c839e5aec 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Asn1/X509ExtensionAsn.manual.cs @@ -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; diff --git a/src/libraries/Common/src/System/Security/Cryptography/CngPkcs8.cs b/src/libraries/Common/src/System/Security/Cryptography/CngPkcs8.cs index a57b6b25504bf7..8d086244207ac9 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/CngPkcs8.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/CngPkcs8.cs @@ -34,8 +34,10 @@ internal static bool IsPlatformScheme(PbeParameters pbeParameters) internal static byte[] ExportEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs b/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs index afd98dee93e7ff..d58f99ded5ce82 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs @@ -206,8 +206,10 @@ protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) protected override bool TryHashData(ReadOnlySpan data, Span 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 @@ private static ReadOnlySpan SignHash( 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)rgbHash, (ReadOnlySpan)rgbSignature); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs index 7f6c02d6bfadca..c481a9479a6600 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs @@ -75,8 +75,10 @@ public override void ImportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -85,8 +87,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -105,10 +109,12 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -124,10 +130,12 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSACng.SignVerify.cs b/src/libraries/Common/src/System/Security/Cryptography/DSACng.SignVerify.cs index 97b29874bc709a..c076e8c9a68b45 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSACng.SignVerify.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSACng.SignVerify.cs @@ -17,8 +17,10 @@ public sealed partial class DSACng : DSA // 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 stackBuf = stackalloc byte[WindowsMaxQSize]; ReadOnlySpan source = AdjustHashSizeIfNecessary(rgbHash, stackBuf); @@ -68,8 +70,11 @@ protected override unsafe bool TryCreateSignatureCore( 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); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs index 3f2479b27ec2c0..b00ee1df2ab7ef 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs @@ -193,8 +193,10 @@ private SafeDsaHandle GenerateKey() 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 @@ private static ReadOnlySpan SignHash( 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)rgbHash, (ReadOnlySpan)rgbSignature); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs index 4fc9783a92b499..af62e79694c4a2 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs @@ -66,8 +66,10 @@ public override int KeySize } } - 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 @@ public override byte[] CreateSignature(byte[] rgbHash!!) 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)hash, (ReadOnlySpan)signature); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroid.Derive.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroid.Derive.cs index ee454e95a39e52..4c266209ea6f33 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroid.Derive.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroid.Derive.cs @@ -18,11 +18,12 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl 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 @@ public override byte[] DeriveKeyFromHash( } 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 @@ public override byte[] DeriveKeyFromHmac( (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( diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroidPublicKey.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroidPublicKey.cs index 084fc08dccc4b7..b6f3b04f360867 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroidPublicKey.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroidPublicKey.cs @@ -11,8 +11,10 @@ internal sealed class ECDiffieHellmanAndroidPublicKey : ECDiffieHellmanPublicKey { 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)); diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.ImportExport.cs index 1799aad9771ff5..2dc7e613b72c8b 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.ImportExport.cs @@ -165,8 +165,10 @@ private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -175,8 +177,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -195,10 +199,12 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -214,10 +220,12 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.cs index a33996933c6dfb..f61f2326e8bebb 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.cs @@ -71,11 +71,12 @@ public override KeySizes[] LegalKeySizes } 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 @@ public override byte[] DeriveKeyFromHash( } 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 @@ public override byte[] DeriveKeyFromHmac( } } - 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( diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs index f31d79f5662d6b..734047e7e255b6 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs @@ -15,11 +15,12 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl 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 @@ public override byte[] DeriveKeyFromHash( } 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 @@ public override byte[] DeriveKeyFromHmac( (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( diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs index 9c783f2b3ee5f5..07c03ee0788f7c 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs @@ -9,8 +9,10 @@ internal sealed class ECDiffieHellmanOpenSslPublicKey : ECDiffieHellmanPublicKey { 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)); diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanSecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanSecurityTransforms.cs index 763c1fa1464414..9033c3af00c4f7 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanSecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanSecurityTransforms.cs @@ -121,11 +121,12 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl 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 @@ public override byte[] DeriveKeyFromHash( } 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 @@ public override byte[] DeriveKeyFromHmac( (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( diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDsaAndroid.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDsaAndroid.cs index 95b7b5c0422f7c..6fdb82e3a7b346 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaAndroid.cs @@ -79,8 +79,10 @@ public override KeySizes[] LegalKeySizes } } - 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 @@ private static ReadOnlySpan SignHash( 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)hash, (ReadOnlySpan)signature); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.ImportExport.cs index 867e2d93f61a8a..0eb393a4f2516c 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.ImportExport.cs @@ -182,8 +182,10 @@ private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -192,8 +194,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -212,10 +216,12 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -231,10 +237,12 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.SignVerify.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.SignVerify.cs index 4b5102319f8f7f..e8e2567cf4c9d6 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.SignVerify.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.SignVerify.cs @@ -16,8 +16,10 @@ public sealed partial class ECDsaCng : ECDsa /// /// Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm." /// - 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 @@ protected override unsafe bool TrySignHashCore( /// /// Verifies that alleged signature of a hash is, in fact, a valid signature of that hash. /// - 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); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDsaOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDsaOpenSsl.cs index a405efcca5960e..898aa902e2642a 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaOpenSsl.cs @@ -89,8 +89,10 @@ public override KeySizes[] LegalKeySizes } } - 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 @@ private static ReadOnlySpan SignHash( 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)hash, (ReadOnlySpan)signature); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECDsaSecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/ECDsaSecurityTransforms.cs index e988595931f71c..7eaeb3b0b360db 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaSecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaSecurityTransforms.cs @@ -57,8 +57,10 @@ public override int KeySize } } - 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 @@ public override bool TrySignHash(ReadOnlySpan source, Span destinati } } - 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)hash, (ReadOnlySpan)signature); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs b/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs index ce28ddb440e866..7b5e4756cb0391 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs @@ -73,8 +73,11 @@ public override KeySizes[] LegalKeySizes } } - 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 @@ public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) public override bool TryDecrypt( ReadOnlySpan data, Span 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 @@ private static bool TryDecrypt( } } - 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 @@ public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) return buf; } - public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding!!, out int bytesWritten) + public override bool TryEncrypt(ReadOnlySpan data, Span 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 @@ private bool TrySignHash( } 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(hash), new ReadOnlySpan(signature), hashAlgorithm, padding); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs index 70c757230df07d..6eff403df797b6 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs @@ -34,8 +34,11 @@ public override bool TryDecrypt(ReadOnlySpan data, Span destination, // 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 @@ private unsafe byte[] EncryptOrDecrypt(byte[] data!!, RSAEncryptionPadding paddi // 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 data, Span destination, RSAEncryptionPadding padding!!, bool encrypt, out int bytesWritten) + private unsafe bool TryEncryptOrDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, bool encrypt, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(padding); + int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); if (!encrypt && data.Length != modulusSizeInBytes) diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs b/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs index 00db1b73074ffd..928bf654c93365 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs @@ -191,8 +191,10 @@ private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -201,8 +203,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -221,10 +225,12 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -240,10 +246,12 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSACng.SignVerify.cs b/src/libraries/Common/src/System/Security/Cryptography/RSACng.SignVerify.cs index b9e3a41e6171c9..c8b5e63d26c5d9 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.SignVerify.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.SignVerify.cs @@ -40,11 +40,11 @@ private static int GetHashSizeInBytes(HashAlgorithmName hashAlgorithm) /// /// Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm." /// - 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 @@ public override unsafe bool TrySignHash(ReadOnlySpan hash, Span dest /// /// Verifies that alleged signature of a hash is, in fact, a valid signature of that hash. /// - 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)hash, (ReadOnlySpan)signature, hashAlgorithm, padding); } diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs index 962afe991a1979..609e75720b6315 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs @@ -80,8 +80,11 @@ public override KeySizes[] LegalKeySizes } } - 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 @@ public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) public override bool TryDecrypt( ReadOnlySpan data, Span 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 @@ private static int Decrypt( 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 @@ public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) return buf; } - public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding!!, out int bytesWritten) + public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(padding); + ValidatePadding(padding); SafeEvpPKeyHandle? key = GetKey(); @@ -801,11 +811,14 @@ private bool TrySignHash( } 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(hash), new ReadOnlySpan(signature), hashAlgorithm, padding); } @@ -845,8 +858,10 @@ private static ReadOnlyMemory VerifyPkcs8(ReadOnlyMemory pkcs8) } } - 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 @@ private static void ValidatePadding(RSAEncryptionPadding padding!!) } } - 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. diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs index 56cf48bc9703aa..6764bb537f3fc9 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs @@ -207,8 +207,11 @@ public override void ImportEncryptedPkcs8PrivateKey( 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 @@ public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) return output; } - public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding!!, out int bytesWritten) + public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(padding); + ThrowIfDisposed(); int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); @@ -289,8 +294,11 @@ public override bool TryEncrypt(ReadOnlySpan data, Span destination, 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 @@ public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding); } - public override bool TryDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding!!, out int bytesWritten) + public override bool TryDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(padding); + SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) @@ -483,11 +493,14 @@ public override bool TrySignHash(ReadOnlySpan hash, Span destination } 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)hash, (ReadOnlySpan)signature, hashAlgorithm, padding); } diff --git a/src/libraries/Common/src/System/Text/DBCSDecoder.cs b/src/libraries/Common/src/System/Text/DBCSDecoder.cs index 430ae57db1740d..b453e2187c68f8 100644 --- a/src/libraries/Common/src/System/Text/DBCSDecoder.cs +++ b/src/libraries/Common/src/System/Text/DBCSDecoder.cs @@ -45,8 +45,10 @@ public override int GetCharCount(byte[] bytes, int index, int count) 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 @@ private unsafe int ConvertWithLeftOverByte(byte* bytes, int count, char* chars, 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 @@ public override int GetChars(byte[] bytes, int byteIndex, int byteCount, 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 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount } } - 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 @@ public unsafe override int GetChars(byte* bytes!!, int byteCount, char* chars!!, 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 @@ public override unsafe void Convert(byte[] bytes!!, int byteIndex, int byteCount } } - 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); diff --git a/src/libraries/Common/src/System/Text/OSEncoder.cs b/src/libraries/Common/src/System/Text/OSEncoder.cs index f6c618870ebc6c..fa14f565195a80 100644 --- a/src/libraries/Common/src/System/Text/OSEncoder.cs +++ b/src/libraries/Common/src/System/Text/OSEncoder.cs @@ -25,8 +25,10 @@ public override void Reset() _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 @@ private unsafe int ConvertWithLeftOverChar(char* chars, int count, byte* bytes, 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 @@ public unsafe override int GetByteCount(char* chars!!, int count, bool flush) 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 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount } } - 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 @@ public unsafe override int GetBytes(char* chars!!, int charCount, byte* bytes!!, 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 @@ public override unsafe void Convert(char[] chars!!, int charIndex, int charCount } } - 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); diff --git a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs index ff3f3510c6c5b3..076cb19b581333 100644 --- a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs +++ b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs @@ -17,8 +17,10 @@ internal OSEncoding(int codePage) : base(codePage) _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 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count) } } - 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 @@ public override unsafe int GetByteCount(string s!!) } } - 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 @@ public override unsafe int GetBytes(string s!!, int charIndex, int charCount, by } } - 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 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount } } - 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 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) } } - 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); diff --git a/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs b/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs index fbaf7a0d9bff6c..a308e1d9f61a54 100644 --- a/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs @@ -63,8 +63,12 @@ public static TResult End(IAsyncResult asyncResult) /// Throws an argument exception for the invalid . [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)); + } /// Provides a simple IAsyncResult that wraps a Task. /// diff --git a/src/libraries/Common/src/System/ThrowHelper.cs b/src/libraries/Common/src/System/ThrowHelper.cs new file mode 100644 index 00000000000000..962dcbacfc7a0e --- /dev/null +++ b/src/libraries/Common/src/System/ThrowHelper.cs @@ -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 + { + /// Throws an if is null. + /// The reference type argument to validate as non-null. + /// The name of the parameter with which corresponds. + 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 diff --git a/src/libraries/Common/tests/System/Xml/ModuleCore/ctestexception.cs b/src/libraries/Common/tests/System/Xml/ModuleCore/ctestexception.cs index 0467c7b4d574f7..af5b3db90296a6 100644 --- a/src/libraries/Common/tests/System/Xml/ModuleCore/ctestexception.cs +++ b/src/libraries/Common/tests/System/Xml/ModuleCore/ctestexception.cs @@ -58,19 +58,32 @@ public class CTestException : Exception 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; diff --git a/src/libraries/Common/tests/System/Xml/XmlCoreTest/FilePathUtil.cs b/src/libraries/Common/tests/System/Xml/XmlCoreTest/FilePathUtil.cs index 6f5e326ae01a5a..76bf378b00c4be 100644 --- a/src/libraries/Common/tests/System/Xml/XmlCoreTest/FilePathUtil.cs +++ b/src/libraries/Common/tests/System/Xml/XmlCoreTest/FilePathUtil.cs @@ -173,8 +173,10 @@ public static Stream getStream(string filename) } } - public static void addStream(string filename, MemoryStream s!!) + public static void addStream(string filename, MemoryStream s) { + ArgumentNullException.ThrowIfNull(s); + if (null == filename) return; diff --git a/src/libraries/Microsoft.Bcl.AsyncInterfaces/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs b/src/libraries/Microsoft.Bcl.AsyncInterfaces/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs index 713ee8d0f80247..87dd49c49fb714 100644 --- a/src/libraries/Microsoft.Bcl.AsyncInterfaces/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs +++ b/src/libraries/Microsoft.Bcl.AsyncInterfaces/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs @@ -113,8 +113,12 @@ public TResult GetResult(short token) /// The state object to pass to when it's invoked. /// Opaque value that was provided to the 's constructor. /// The flags describing the behavior of the continuation. - public void OnCompleted(Action continuation!!, object state, short token, ValueTaskSourceOnCompletedFlags flags) + public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { + if (continuation is null) + { + throw new ArgumentNullException(nameof(continuation)); + } ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) diff --git a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs index d6b506cc1c6379..6cbafb5309683a 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs @@ -30,8 +30,10 @@ public static ICacheEntry SetPriority( /// The for chaining. public static ICacheEntry AddExpirationToken( this ICacheEntry entry, - IChangeToken expirationToken!!) + IChangeToken expirationToken) { + ThrowHelper.ThrowIfNull(expirationToken); + entry.ExpirationTokens.Add(expirationToken); return entry; } @@ -87,8 +89,10 @@ public static ICacheEntry SetSlidingExpiration( /// The for chaining. public static ICacheEntry RegisterPostEvictionCallback( this ICacheEntry entry, - PostEvictionDelegate callback!!) + PostEvictionDelegate callback) { + ThrowHelper.ThrowIfNull(callback); + return entry.RegisterPostEvictionCallback(callback, state: null); } @@ -101,9 +105,11 @@ public static ICacheEntry RegisterPostEvictionCallback( /// The for chaining. 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 @@ public static ICacheEntry SetSize( /// The . /// Set the values of these options on the . /// The for chaining. - 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; diff --git a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/DistributedCacheExtensions.cs b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/DistributedCacheExtensions.cs index 1793665d5222f6..4b9f396ff0b9c4 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/DistributedCacheExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/DistributedCacheExtensions.cs @@ -20,8 +20,11 @@ public static class DistributedCacheExtensions /// The key to store the data in. /// The data to store in the cache. /// Thrown when or is null. - 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 @@ public static void Set(this IDistributedCache cache, string key!!, byte[] value! /// Optional. A to cancel the operation. /// A task that represents the asynchronous set operation. /// Thrown when or is null. - 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 @@ public static void SetString(this IDistributedCache cache, string key, string va /// The data to store in the cache. /// The cache options for the entry. /// Thrown when or is null. - 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 @@ public static void SetString(this IDistributedCache cache, string key!!, string /// Optional. A to cancel the operation. /// A task that represents the asynchronous set operation. /// Thrown when or is null. - 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); } diff --git a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/MemoryCacheEntryExtensions.cs b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/MemoryCacheEntryExtensions.cs index b102cfc6485d47..aab7cf5ae05773 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/MemoryCacheEntryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/MemoryCacheEntryExtensions.cs @@ -49,8 +49,10 @@ public static MemoryCacheEntryOptions SetSize( /// The so that additional calls can be chained. public static MemoryCacheEntryOptions AddExpirationToken( this MemoryCacheEntryOptions options, - IChangeToken expirationToken!!) + IChangeToken expirationToken) { + ThrowHelper.ThrowIfNull(expirationToken); + options.ExpirationTokens.Add(expirationToken); return options; } @@ -106,8 +108,10 @@ public static MemoryCacheEntryOptions SetSlidingExpiration( /// The so that additional calls can be chained. public static MemoryCacheEntryOptions RegisterPostEvictionCallback( this MemoryCacheEntryOptions options, - PostEvictionDelegate callback!!) + PostEvictionDelegate callback) { + ThrowHelper.ThrowIfNull(callback); + return options.RegisterPostEvictionCallback(callback, state: null); } @@ -120,9 +124,11 @@ public static MemoryCacheEntryOptions RegisterPostEvictionCallback( /// The so that additional calls can be chained. public static MemoryCacheEntryOptions RegisterPostEvictionCallback( this MemoryCacheEntryOptions options, - PostEvictionDelegate callback!!, + PostEvictionDelegate callback, object? state) { + ThrowHelper.ThrowIfNull(callback); + options.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = callback, diff --git a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/Microsoft.Extensions.Caching.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/Microsoft.Extensions.Caching.Abstractions.csproj index 25d77c9de8c998..9c91e7e1647f65 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/Microsoft.Extensions.Caching.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/Microsoft.Extensions.Caching.Abstractions.csproj @@ -16,6 +16,8 @@ Microsoft.Extensions.Caching.Memory.IMemoryCache + diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs index a090f5e70716eb..677786a71bdcc4 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs @@ -25,8 +25,11 @@ internal sealed partial class CacheEntry : ICacheEntry 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; diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs index 127b2250f592c6..a8ee2410194f57 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs @@ -44,8 +44,11 @@ public MemoryCache(IOptions optionsAccessor) /// /// The options of the cache. /// The factory used to create loggers. - public MemoryCache(IOptions optionsAccessor!!, ILoggerFactory loggerFactory!!) + public MemoryCache(IOptions optionsAccessor, ILoggerFactory loggerFactory) { + ThrowHelper.ThrowIfNull(optionsAccessor); + ThrowHelper.ThrowIfNull(loggerFactory); + _options = optionsAccessor.Value; _logger = loggerFactory.CreateLogger(); @@ -205,8 +208,10 @@ internal void SetEntry(CacheEntry entry) } /// - 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 @@ public bool TryGetValue(object key!!, out object? result) } /// - 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 @@ private void CheckDisposed() 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 diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCacheServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCacheServiceCollectionExtensions.cs index 6e754b5d9c9f15..b8d443cbac1989 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCacheServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCacheServiceCollectionExtensions.cs @@ -19,8 +19,10 @@ public static class MemoryCacheServiceCollectionExtensions /// /// The to add services to. /// The so that additional calls can be chained. - public static IServiceCollection AddMemoryCache(this IServiceCollection services!!) + public static IServiceCollection AddMemoryCache(this IServiceCollection services) { + ThrowHelper.ThrowIfNull(services); + services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); @@ -36,8 +38,11 @@ public static IServiceCollection AddMemoryCache(this IServiceCollection services /// The to configure the provided . /// /// The so that additional calls can be chained. - public static IServiceCollection AddMemoryCache(this IServiceCollection services!!, Action setupAction!!) + public static IServiceCollection AddMemoryCache(this IServiceCollection services, Action setupAction) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(setupAction); + services.AddMemoryCache(); services.Configure(setupAction); @@ -58,8 +63,10 @@ public static IServiceCollection AddMemoryCache(this IServiceCollection services /// /// The to add services to. /// The so that additional calls can be chained. - public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services!!) + public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services) { + ThrowHelper.ThrowIfNull(services); + services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); @@ -83,8 +90,11 @@ public static IServiceCollection AddDistributedMemoryCache(this IServiceCollecti /// The to configure the provided . /// /// The so that additional calls can be chained. - public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services!!, Action setupAction!!) + public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services, Action setupAction) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(setupAction); + services.AddDistributedMemoryCache(); services.Configure(setupAction); diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs index d4e7ec432db116..cb0b241de87c40 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs @@ -18,23 +18,34 @@ public class MemoryDistributedCache : IDistributedCache public MemoryDistributedCache(IOptions optionsAccessor) : this(optionsAccessor, NullLoggerFactory.Instance) { } - public MemoryDistributedCache(IOptions optionsAccessor!!, ILoggerFactory loggerFactory!!) + public MemoryDistributedCache(IOptions 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 GetAsync(string key!!, CancellationToken token = default(CancellationToken)) + public Task 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 @@ public void Set(string key!!, byte[] value!!, DistributedCacheEntryOptions optio _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; } diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj b/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj index a0b48782b5453b..793cde7c951864 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj @@ -16,6 +16,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs index d10c4bdfd1bc88..681ffc0dfaff23 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs @@ -94,8 +94,10 @@ public static bool Exists([NotNullWhen(true)] this IConfigurationSection? sectio /// If no matching sub-section is found with the specified key, an exception is raised. /// /// There is no section with key . - public static IConfigurationSection GetRequiredSection(this IConfiguration configuration!!, string key) + public static IConfigurationSection GetRequiredSection(this IConfiguration configuration, string key) { + ThrowHelper.ThrowIfNull(configuration); + IConfigurationSection section = configuration.GetSection(key); if (section.Exists()) { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationPath.cs b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationPath.cs index 0ee4036cca37c5..c48c0d4a2ba041 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationPath.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationPath.cs @@ -22,8 +22,10 @@ public static class ConfigurationPath /// /// The path segments to combine. /// The combined path. - public static string Combine(params string[] pathSegments!!) + public static string Combine(params string[] pathSegments) { + ThrowHelper.ThrowIfNull(pathSegments); + return string.Join(KeyDelimiter, pathSegments); } @@ -32,8 +34,10 @@ public static string Combine(params string[] pathSegments!!) /// /// The path segments to combine. /// The combined path. - public static string Combine(IEnumerable pathSegments!!) + public static string Combine(IEnumerable pathSegments) { + ThrowHelper.ThrowIfNull(pathSegments); + return string.Join(KeyDelimiter, pathSegments); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/Microsoft.Extensions.Configuration.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/Microsoft.Extensions.Configuration.Abstractions.csproj index f167e3fa276b5a..928f923fb7509b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/Microsoft.Extensions.Configuration.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/Microsoft.Extensions.Configuration.Abstractions.csproj @@ -19,6 +19,8 @@ Microsoft.Extensions.Configuration.IConfigurationSection + diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs index ec8819fdae0655..e56a0875bd46ec 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs @@ -44,8 +44,10 @@ public static class ConfigurationBinder /// Configures the binder options. /// The new instance of T if successful, default(T) otherwise. [RequiresUnreferencedCode(TrimmingWarningMessage)] - public static T? Get<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration!!, Action? configureOptions) + public static T? Get<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(this IConfiguration configuration, Action? configureOptions) { + ThrowHelper.ThrowIfNull(configuration); + object? result = configuration.Get(typeof(T), configureOptions); if (result == null) { @@ -77,11 +79,13 @@ public static class ConfigurationBinder /// The new instance if successful, null otherwise. [RequiresUnreferencedCode(TrimmingWarningMessage)] public static object? Get( - this IConfiguration configuration!!, + this IConfiguration configuration, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, Action? configureOptions) { + ThrowHelper.ThrowIfNull(configuration); + var options = new BinderOptions(); configureOptions?.Invoke(options); var bindingPoint = new BindingPoint(); @@ -115,8 +119,10 @@ public static void Bind(this IConfiguration configuration, object? instance) /// The object to bind. /// Configures the binder options. [RequiresUnreferencedCode(InstanceGetTypeTrimmingWarningMessage)] - public static void Bind(this IConfiguration configuration!!, object? instance, Action? configureOptions) + public static void Bind(this IConfiguration configuration, object? instance, Action? configureOptions) { + ThrowHelper.ThrowIfNull(configuration); + if (instance != null) { var options = new BinderOptions(); @@ -681,8 +687,10 @@ private static List GetAllProperties( return allProperties; } - private static string GetPropertyName(MemberInfo property!!) + private static string GetPropertyName(MemberInfo property) { + ThrowHelper.ThrowIfNull(property); + // Check for a custom property name used for configuration key binding foreach (var attributeData in property.GetCustomAttributesData()) { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/Microsoft.Extensions.Configuration.Binder.csproj b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/Microsoft.Extensions.Configuration.Binder.csproj index e6bbd1039b3dd3..eda41631b2feac 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/Microsoft.Extensions.Configuration.Binder.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/Microsoft.Extensions.Configuration.Binder.csproj @@ -12,6 +12,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs index 67a3256aa510c0..e938472f476cf7 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs @@ -18,8 +18,10 @@ public class CommandLineConfigurationProvider : ConfigurationProvider /// /// The command line args. /// The switch mappings. - public CommandLineConfigurationProvider(IEnumerable args!!, IDictionary? switchMappings = null) + public CommandLineConfigurationProvider(IEnumerable args, IDictionary? switchMappings = null) { + ThrowHelper.ThrowIfNull(args); + Args = args; if (switchMappings != null) diff --git a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj index a7b12e2099e6f5..b21a58a19263db 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/Microsoft.Extensions.Configuration.CommandLine.csproj @@ -13,6 +13,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs index 072e398f2c7c33..5b8e2a8942e18b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs @@ -20,8 +20,11 @@ public static class FileConfigurationExtensions /// The to add to. /// The default file provider instance. /// The . - public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder builder!!, IFileProvider fileProvider!!) + public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder builder, IFileProvider fileProvider) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(fileProvider); + builder.Properties[FileProviderKey] = fileProvider; return builder; } @@ -31,8 +34,10 @@ public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder b /// /// The . /// The default . - public static IFileProvider GetFileProvider(this IConfigurationBuilder builder!!) + public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) { + ThrowHelper.ThrowIfNull(builder); + if (builder.Properties.TryGetValue(FileProviderKey, out object? provider)) { return (IFileProvider)provider; @@ -47,8 +52,11 @@ public static IFileProvider GetFileProvider(this IConfigurationBuilder builder!! /// The to add to. /// The absolute path of file-based providers. /// The . - public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder!!, string basePath!!) + public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder, string basePath) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(basePath); + return builder.SetFileProvider(new PhysicalFileProvider(basePath)); } @@ -58,8 +66,10 @@ public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder build /// The to add to. /// The Action to be invoked on a file load exception. /// The . - public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurationBuilder builder!!, Action handler) + public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurationBuilder builder, Action handler) { + ThrowHelper.ThrowIfNull(builder); + builder.Properties[FileLoadExceptionHandlerKey] = handler; return builder; } @@ -69,8 +79,10 @@ public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurat /// /// The . /// The . - public static Action? GetFileLoadExceptionHandler(this IConfigurationBuilder builder!!) + public static Action? GetFileLoadExceptionHandler(this IConfigurationBuilder builder) { + ThrowHelper.ThrowIfNull(builder); + if (builder.Properties.TryGetValue(FileLoadExceptionHandlerKey, out object? handler)) { return handler as Action; diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs index a8620f0bdbe850..d226051b1ab838 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs @@ -23,8 +23,10 @@ public abstract class FileConfigurationProvider : ConfigurationProvider, IDispos /// Initializes a new instance with the specified source. /// /// The source settings. - public FileConfigurationProvider(FileConfigurationSource source!!) + public FileConfigurationProvider(FileConfigurationSource source) { + ThrowHelper.ThrowIfNull(source); + Source = source; if (Source.ReloadOnChange && Source.FileProvider != null) diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj index e2c041ade18337..4702a043f63382 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj @@ -16,6 +16,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs index 2c3802993713e8..8331591b21562a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs @@ -62,8 +62,10 @@ public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builde /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. /// The . - public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder!!, IFileProvider? provider, string path, bool optional, bool reloadOnChange) + public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { + ThrowHelper.ThrowIfNull(builder); + if (string.IsNullOrEmpty(path)) { throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path)); @@ -94,8 +96,10 @@ public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builde /// The to add to. /// The to read the ini configuration data from. /// The . - public static IConfigurationBuilder AddIniStream(this IConfigurationBuilder builder!!, Stream stream) + public static IConfigurationBuilder AddIniStream(this IConfigurationBuilder builder, Stream stream) { + ThrowHelper.ThrowIfNull(builder); + return builder.Add(s => s.Stream = stream); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj index a212999573c808..701b278d091ba8 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj @@ -15,6 +15,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs index b49c1a8642d4ff..c32d20f75943a5 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs @@ -62,8 +62,10 @@ public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder build /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. /// The . - public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder!!, IFileProvider? provider, string path, bool optional, bool reloadOnChange) + public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { + ThrowHelper.ThrowIfNull(builder); + if (string.IsNullOrEmpty(path)) { throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path)); @@ -94,8 +96,10 @@ public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder build /// The to add to. /// The to read the json configuration data from. /// The . - public static IConfigurationBuilder AddJsonStream(this IConfigurationBuilder builder!!, Stream stream) + public static IConfigurationBuilder AddJsonStream(this IConfigurationBuilder builder, Stream stream) { + ThrowHelper.ThrowIfNull(builder); + return builder.Add(s => s.Stream = stream); } } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj index d4f9da6c374a12..3ffd9b21b8eb3a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj @@ -17,6 +17,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj index 3ef1609424bf86..be5d0b6ac45bad 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj @@ -15,6 +15,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs index db166c2c88d4a2..9a1577f1559817 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs @@ -116,8 +116,11 @@ public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder co /// Whether the configuration should be reloaded if the file changes. /// Thrown when is false and does not have a valid . /// The configuration builder. - public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration!!, Assembly assembly!!, bool optional, bool reloadOnChange) + public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional, bool reloadOnChange) { + ThrowHelper.ThrowIfNull(configuration); + ThrowHelper.ThrowIfNull(assembly); + UserSecretsIdAttribute? attribute = assembly.GetCustomAttribute(); if (attribute != null) { @@ -161,8 +164,11 @@ public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder co public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange) => AddUserSecretsInternal(configuration, userSecretsId, true, reloadOnChange); - private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration!!, string userSecretsId!!, bool optional, bool reloadOnChange) + private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration, string userSecretsId, bool optional, bool reloadOnChange) { + ThrowHelper.ThrowIfNull(configuration); + ThrowHelper.ThrowIfNull(userSecretsId); + return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), optional, reloadOnChange); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj index 2f7d296028878c..7831102c2eb578 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj @@ -16,6 +16,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs index ec51d7cdacd7f4..dba4fc6947b429 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -31,8 +31,10 @@ internal sealed class XmlConfigurationElement public List? Attributes { get; set; } - public XmlConfigurationElement(string elementName!!, string? name) + public XmlConfigurationElement(string elementName, string? name) { + ThrowHelper.ThrowIfNull(elementName); + ElementName = elementName; Name = name; SiblingName = string.IsNullOrEmpty(Name) ? ElementName : ElementName + ":" + Name; diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs index ea9efc1c84d4c7..2eae9a3c4e701e 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -7,8 +7,11 @@ namespace Microsoft.Extensions.Configuration.Xml { internal sealed class XmlConfigurationElementAttributeValue { - public XmlConfigurationElementAttributeValue(string attribute!!, string value!!, int? lineNumber, int? linePosition) + public XmlConfigurationElementAttributeValue(string attribute, string value, int? lineNumber, int? linePosition) { + ThrowHelper.ThrowIfNull(attribute); + ThrowHelper.ThrowIfNull(value); + Attribute = attribute; Value = value; LineNumber = lineNumber; diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs index d5f5d38498937f..ee25d5cfdb6bf8 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; @@ -7,8 +7,10 @@ namespace Microsoft.Extensions.Configuration.Xml { internal sealed class XmlConfigurationElementTextContent { - public XmlConfigurationElementTextContent(string textContent!!, int? linePosition, int? lineNumber) + public XmlConfigurationElementTextContent(string textContent, int? linePosition, int? lineNumber) { + ThrowHelper.ThrowIfNull(textContent); + TextContent = textContent; LineNumber = lineNumber; LinePosition = linePosition; diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs index a45173b132cff4..e0d1cee1a6c29a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs @@ -62,8 +62,10 @@ public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builde /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. /// The . - public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builder!!, IFileProvider? provider, string path, bool optional, bool reloadOnChange) + public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { + ThrowHelper.ThrowIfNull(builder); + if (string.IsNullOrEmpty(path)) { throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path)); @@ -94,8 +96,10 @@ public static IConfigurationBuilder AddXmlFile(this IConfigurationBuilder builde /// The to add to. /// The to read the XML configuration data from. /// The . - public static IConfigurationBuilder AddXmlStream(this IConfigurationBuilder builder!!, Stream stream) + public static IConfigurationBuilder AddXmlStream(this IConfigurationBuilder builder, Stream stream) { + ThrowHelper.ThrowIfNull(builder); + return builder.Add(s => s.Stream = stream); } } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs index 118bacffe74a20..f6e013fa1c356a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs @@ -27,8 +27,11 @@ public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder /// The to add. /// Whether the configuration should get disposed when the configuration provider is disposed. /// The . - public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder!!, IConfiguration config!!, bool shouldDisposeConfiguration) + public static IConfigurationBuilder AddConfiguration(this IConfigurationBuilder configurationBuilder, IConfiguration config, bool shouldDisposeConfiguration) { + ThrowHelper.ThrowIfNull(configurationBuilder); + ThrowHelper.ThrowIfNull(config); + configurationBuilder.Add(new ChainedConfigurationSource { Configuration = config, diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs index c5d46497155e8d..4cfe5db2dd1402 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -19,8 +19,10 @@ public class ChainedConfigurationProvider : IConfigurationProvider, IDisposable /// Initialize a new instance from the source configuration. /// /// The source configuration. - public ChainedConfigurationProvider(ChainedConfigurationSource source!!) + public ChainedConfigurationProvider(ChainedConfigurationSource source) { + ThrowHelper.ThrowIfNull(source); + _config = source.Configuration ?? throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Configuration"), nameof(source)); _shouldDisposeConfig = source.ShouldDisposeConfiguration; } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs index c0675526e94248..f49a822fc62b2c 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs @@ -27,8 +27,10 @@ public class ConfigurationBuilder : IConfigurationBuilder /// /// The configuration source to add. /// The same . - public IConfigurationBuilder Add(IConfigurationSource source!!) + public IConfigurationBuilder Add(IConfigurationSource source) { + ThrowHelper.ThrowIfNull(source); + Sources.Add(source); return this; } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs index 89aa77eb68ccc9..5b27bfb8ccbe21 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs @@ -81,8 +81,10 @@ public void Dispose() _providerManager.Dispose(); } - IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source!!) + IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) { + ThrowHelper.ThrowIfNull(source); + _sources.Add(source); return this; } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs index ae0e1e6bb52af5..74f53a8d6c6bb2 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs @@ -21,8 +21,10 @@ public class ConfigurationRoot : IConfigurationRoot, IDisposable /// Initializes a Configuration root with a list of providers. /// /// The s for this configuration. - public ConfigurationRoot(IList providers!!) + public ConfigurationRoot(IList providers) { + ThrowHelper.ThrowIfNull(providers); + _providers = providers; _changeTokenRegistrations = new List(providers.Count); foreach (IConfigurationProvider p in providers) diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs index 35996f15afec13..c9c4c8baaf5be4 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs @@ -21,8 +21,11 @@ public class ConfigurationSection : IConfigurationSection /// /// The configuration root. /// The path to this section. - public ConfigurationSection(IConfigurationRoot root!!, string path!!) + public ConfigurationSection(IConfigurationRoot root, string path) { + ThrowHelper.ThrowIfNull(root); + ThrowHelper.ThrowIfNull(path); + _root = root; _path = path; } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs index 781d37effe0456..34998f40101d35 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs @@ -17,8 +17,10 @@ public static class MemoryConfigurationBuilderExtensions /// /// The to add to. /// The . - public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder!!) + public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder) { + ThrowHelper.ThrowIfNull(configurationBuilder); + configurationBuilder.Add(new MemoryConfigurationSource()); return configurationBuilder; } @@ -30,9 +32,11 @@ public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBui /// The data to add to memory configuration provider. /// The . public static IConfigurationBuilder AddInMemoryCollection( - this IConfigurationBuilder configurationBuilder!!, + this IConfigurationBuilder configurationBuilder, IEnumerable>? initialData) { + ThrowHelper.ThrowIfNull(configurationBuilder); + configurationBuilder.Add(new MemoryConfigurationSource { InitialData = initialData }); return configurationBuilder; } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs index 1e2c17fb6e764c..4e0774702b11c0 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs @@ -18,8 +18,10 @@ public class MemoryConfigurationProvider : ConfigurationProvider, IEnumerable /// The source settings. - public MemoryConfigurationProvider(MemoryConfigurationSource source!!) + public MemoryConfigurationProvider(MemoryConfigurationSource source) { + ThrowHelper.ThrowIfNull(source); + _source = source; if (_source.InitialData != null) diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj b/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj index 0f2a92e5a9a39d..6b771601b4b265 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration/src/Microsoft.Extensions.Configuration.csproj @@ -13,6 +13,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs index 8d6b4b3866cb92..58bf27d0482c3a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs @@ -22,8 +22,10 @@ public abstract class StreamConfigurationProvider : ConfigurationProvider /// Constructor. /// /// The source. - public StreamConfigurationProvider(StreamConfigurationSource source!!) + public StreamConfigurationProvider(StreamConfigurationSource source) { + ThrowHelper.ThrowIfNull(source); + Source = source; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs index 9f0f7b380a17b0..1177b35a869feb 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs @@ -18,8 +18,10 @@ namespace Microsoft.Extensions.DependencyInjection /// Wraps an instance of . /// /// The instance to wrap. - public AsyncServiceScope(IServiceScope serviceScope!!) + public AsyncServiceScope(IServiceScope serviceScope) { + ThrowHelper.ThrowIfNull(serviceScope); + _serviceScope = serviceScope; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs index 7ec5f7c4913ef0..4f99cd94cb85f0 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs @@ -19,9 +19,12 @@ public static class ServiceCollectionDescriptorExtensions /// The to add. /// A reference to the current instance of . public static IServiceCollection Add( - this IServiceCollection collection!!, - ServiceDescriptor descriptor!!) + this IServiceCollection collection, + ServiceDescriptor descriptor) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(descriptor); + collection.Add(descriptor); return collection; } @@ -33,9 +36,12 @@ public static IServiceCollection Add( /// The s to add. /// A reference to the current instance of . public static IServiceCollection Add( - this IServiceCollection collection!!, - IEnumerable descriptors!!) + this IServiceCollection collection, + IEnumerable descriptors) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(descriptors); + foreach (ServiceDescriptor? descriptor in descriptors) { collection.Add(descriptor); @@ -51,9 +57,12 @@ public static IServiceCollection Add( /// The . /// The to add. public static void TryAdd( - this IServiceCollection collection!!, - ServiceDescriptor descriptor!!) + this IServiceCollection collection, + ServiceDescriptor descriptor) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(descriptor); + int count = collection.Count; for (int i = 0; i < count; i++) { @@ -74,9 +83,12 @@ public static void TryAdd( /// The . /// The s to add. public static void TryAdd( - this IServiceCollection collection!!, - IEnumerable descriptors!!) + this IServiceCollection collection, + IEnumerable descriptors) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(descriptors); + foreach (ServiceDescriptor? d in descriptors) { collection.TryAdd(d); @@ -90,9 +102,12 @@ public static void TryAdd( /// The . /// The type of the service to register. public static void TryAddTransient( - this IServiceCollection collection!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service!!) + this IServiceCollection collection, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + var descriptor = ServiceDescriptor.Transient(service, service); TryAdd(collection, descriptor); } @@ -106,10 +121,14 @@ public static void TryAddTransient( /// The type of the service to register. /// The implementation type of the service. public static void TryAddTransient( - this IServiceCollection collection!!, - Type service!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + this IServiceCollection collection, + Type service, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationType); + var descriptor = ServiceDescriptor.Transient(service, implementationType); TryAdd(collection, descriptor); } @@ -123,10 +142,14 @@ public static void TryAddTransient( /// The type of the service to register. /// The factory that creates the service. public static void TryAddTransient( - this IServiceCollection collection!!, - Type service!!, - Func implementationFactory!!) + this IServiceCollection collection, + Type service, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationFactory); + var descriptor = ServiceDescriptor.Transient(service, implementationFactory); TryAdd(collection, descriptor); } @@ -137,9 +160,11 @@ public static void TryAddTransient( /// /// The type of the service to add. /// The . - public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection!!) + public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { + ThrowHelper.ThrowIfNull(collection); + TryAddTransient(collection, typeof(TService), typeof(TService)); } @@ -151,10 +176,12 @@ public static void TryAddTransient( /// The type of the service to add. /// The type of the implementation to use. /// The . - public static void TryAddTransient(this IServiceCollection collection!!) + public static void TryAddTransient(this IServiceCollection collection) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(collection); + TryAddTransient(collection, typeof(TService), typeof(TImplementation)); } @@ -181,9 +208,12 @@ public static void TryAddTransient( /// The . /// The type of the service to register. public static void TryAddScoped( - this IServiceCollection collection!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service!!) + this IServiceCollection collection, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + var descriptor = ServiceDescriptor.Scoped(service, service); TryAdd(collection, descriptor); } @@ -197,10 +227,14 @@ public static void TryAddScoped( /// The type of the service to register. /// The implementation type of the service. public static void TryAddScoped( - this IServiceCollection collection!!, - Type service!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + this IServiceCollection collection, + Type service, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationType); + var descriptor = ServiceDescriptor.Scoped(service, implementationType); TryAdd(collection, descriptor); } @@ -214,10 +248,14 @@ public static void TryAddScoped( /// The type of the service to register. /// The factory that creates the service. public static void TryAddScoped( - this IServiceCollection collection!!, - Type service!!, - Func implementationFactory!!) + this IServiceCollection collection, + Type service, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationFactory); + var descriptor = ServiceDescriptor.Scoped(service, implementationFactory); TryAdd(collection, descriptor); } @@ -228,9 +266,11 @@ public static void TryAddScoped( /// /// The type of the service to add. /// The . - public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection!!) + public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { + ThrowHelper.ThrowIfNull(collection); + TryAddScoped(collection, typeof(TService), typeof(TService)); } @@ -242,10 +282,12 @@ public static void TryAddScoped( /// The type of the service to add. /// The type of the implementation to use. /// The . - public static void TryAddScoped(this IServiceCollection collection!!) + public static void TryAddScoped(this IServiceCollection collection) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(collection); + TryAddScoped(collection, typeof(TService), typeof(TImplementation)); } @@ -272,9 +314,12 @@ public static void TryAddScoped( /// The . /// The type of the service to register. public static void TryAddSingleton( - this IServiceCollection collection!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service!!) + this IServiceCollection collection, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + var descriptor = ServiceDescriptor.Singleton(service, service); TryAdd(collection, descriptor); } @@ -288,10 +333,14 @@ public static void TryAddSingleton( /// The type of the service to register. /// The implementation type of the service. public static void TryAddSingleton( - this IServiceCollection collection!!, - Type service!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + this IServiceCollection collection, + Type service, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationType); + var descriptor = ServiceDescriptor.Singleton(service, implementationType); TryAdd(collection, descriptor); } @@ -305,10 +354,14 @@ public static void TryAddSingleton( /// The type of the service to register. /// The factory that creates the service. public static void TryAddSingleton( - this IServiceCollection collection!!, - Type service!!, - Func implementationFactory!!) + this IServiceCollection collection, + Type service, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationFactory); + var descriptor = ServiceDescriptor.Singleton(service, implementationFactory); TryAdd(collection, descriptor); } @@ -319,9 +372,11 @@ public static void TryAddSingleton( /// /// The type of the service to add. /// The . - public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection!!) + public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class { + ThrowHelper.ThrowIfNull(collection); + TryAddSingleton(collection, typeof(TService), typeof(TService)); } @@ -333,10 +388,12 @@ public static void TryAddSingleton( /// The type of the service to add. /// The type of the implementation to use. /// The . - public static void TryAddSingleton(this IServiceCollection collection!!) + public static void TryAddSingleton(this IServiceCollection collection) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(collection); + TryAddSingleton(collection, typeof(TService), typeof(TImplementation)); } @@ -348,9 +405,12 @@ public static void TryAddSingleton( /// The type of the service to add. /// The . /// The instance of the service to add. - public static void TryAddSingleton(this IServiceCollection collection!!, TService instance!!) + public static void TryAddSingleton(this IServiceCollection collection, TService instance) where TService : class { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(instance); + var descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); TryAdd(collection, descriptor); } @@ -389,9 +449,12 @@ public static void TryAddSingleton( /// of multiple implementation types. /// public static void TryAddEnumerable( - this IServiceCollection services!!, - ServiceDescriptor descriptor!!) + this IServiceCollection services, + ServiceDescriptor descriptor) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(descriptor); + Type? implementationType = descriptor.GetImplementationType(); if (implementationType == typeof(object) || @@ -437,9 +500,12 @@ public static void TryAddEnumerable( /// of multiple implementation types. /// public static void TryAddEnumerable( - this IServiceCollection services!!, - IEnumerable descriptors!!) + this IServiceCollection services, + IEnumerable descriptors) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(descriptors); + foreach (ServiceDescriptor? d in descriptors) { services.TryAddEnumerable(d); @@ -454,9 +520,12 @@ public static void TryAddEnumerable( /// The to replace with. /// The for chaining. public static IServiceCollection Replace( - this IServiceCollection collection!!, - ServiceDescriptor descriptor!!) + this IServiceCollection collection, + ServiceDescriptor descriptor) { + ThrowHelper.ThrowIfNull(collection); + ThrowHelper.ThrowIfNull(descriptor); + // Remove existing int count = collection.Count; for (int i = 0; i < count; i++) @@ -488,8 +557,10 @@ public static IServiceCollection RemoveAll(this IServiceCollection collection /// The . /// The service type to remove. /// The for chaining. - public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType!!) + public static IServiceCollection RemoveAll(this IServiceCollection collection, Type serviceType) { + ThrowHelper.ThrowIfNull(serviceType); + for (int i = collection.Count - 1; i >= 0; i--) { ServiceDescriptor? descriptor = collection[i]; diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj index a2485e4cf64551..7f115ab470ed55 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum) @@ -16,6 +16,8 @@ Microsoft.Extensions.DependencyInjection.IServiceCollection + diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs index 39069984887bfe..c07bde152cffce 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs @@ -22,10 +22,14 @@ public static class ServiceCollectionServiceExtensions /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddTransient( - this IServiceCollection services!!, - Type serviceType!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + this IServiceCollection services, + Type serviceType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationType); + return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } @@ -40,10 +44,14 @@ public static IServiceCollection AddTransient( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddTransient( - this IServiceCollection services!!, - Type serviceType!!, - Func implementationFactory!!) + this IServiceCollection services, + Type serviceType, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationFactory); + return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } @@ -57,10 +65,12 @@ public static IServiceCollection AddTransient( /// The to add the service to. /// A reference to this instance after the operation has completed. /// - public static IServiceCollection AddTransient(this IServiceCollection services!!) + public static IServiceCollection AddTransient(this IServiceCollection services) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(services); + return services.AddTransient(typeof(TService), typeof(TImplementation)); } @@ -73,9 +83,12 @@ public static IServiceCollection AddTransient( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddTransient( - this IServiceCollection services!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType!!) + this IServiceCollection services, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + return services.AddTransient(serviceType, serviceType); } @@ -87,9 +100,11 @@ public static IServiceCollection AddTransient( /// The to add the service to. /// A reference to this instance after the operation has completed. /// - public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services!!) + public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { + ThrowHelper.ThrowIfNull(services); + return services.AddTransient(typeof(TService)); } @@ -104,10 +119,13 @@ public static IServiceCollection AddTransient( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddTransient( - this IServiceCollection services!!, - Func implementationFactory!!) + this IServiceCollection services, + Func implementationFactory) where TService : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationFactory); + return services.AddTransient(typeof(TService), implementationFactory); } @@ -124,11 +142,14 @@ public static IServiceCollection AddTransient( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddTransient( - this IServiceCollection services!!, - Func implementationFactory!!) + this IServiceCollection services, + Func implementationFactory) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationFactory); + return services.AddTransient(typeof(TService), implementationFactory); } @@ -143,10 +164,14 @@ public static IServiceCollection AddTransient( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddScoped( - this IServiceCollection services!!, - Type serviceType!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + this IServiceCollection services, + Type serviceType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationType); + return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } @@ -161,10 +186,14 @@ public static IServiceCollection AddScoped( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddScoped( - this IServiceCollection services!!, - Type serviceType!!, - Func implementationFactory!!) + this IServiceCollection services, + Type serviceType, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationFactory); + return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } @@ -178,10 +207,12 @@ public static IServiceCollection AddScoped( /// The to add the service to. /// A reference to this instance after the operation has completed. /// - public static IServiceCollection AddScoped(this IServiceCollection services!!) + public static IServiceCollection AddScoped(this IServiceCollection services) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(services); + return services.AddScoped(typeof(TService), typeof(TImplementation)); } @@ -194,9 +225,12 @@ public static IServiceCollection AddScoped( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddScoped( - this IServiceCollection services!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType!!) + this IServiceCollection services, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + return services.AddScoped(serviceType, serviceType); } @@ -208,9 +242,11 @@ public static IServiceCollection AddScoped( /// The to add the service to. /// A reference to this instance after the operation has completed. /// - public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services!!) + public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { + ThrowHelper.ThrowIfNull(services); + return services.AddScoped(typeof(TService)); } @@ -225,10 +261,13 @@ public static IServiceCollection AddScoped( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddScoped( - this IServiceCollection services!!, - Func implementationFactory!!) + this IServiceCollection services, + Func implementationFactory) where TService : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationFactory); + return services.AddScoped(typeof(TService), implementationFactory); } @@ -245,11 +284,14 @@ public static IServiceCollection AddScoped( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddScoped( - this IServiceCollection services!!, - Func implementationFactory!!) + this IServiceCollection services, + Func implementationFactory) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationFactory); + return services.AddScoped(typeof(TService), implementationFactory); } @@ -265,10 +307,14 @@ public static IServiceCollection AddScoped( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - Type serviceType!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + this IServiceCollection services, + Type serviceType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationType); + return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } @@ -283,10 +329,14 @@ public static IServiceCollection AddSingleton( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - Type serviceType!!, - Func implementationFactory!!) + this IServiceCollection services, + Type serviceType, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationFactory); + return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } @@ -300,10 +350,12 @@ public static IServiceCollection AddSingleton( /// The to add the service to. /// A reference to this instance after the operation has completed. /// - public static IServiceCollection AddSingleton(this IServiceCollection services!!) + public static IServiceCollection AddSingleton(this IServiceCollection services) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(services); + return services.AddSingleton(typeof(TService), typeof(TImplementation)); } @@ -316,9 +368,12 @@ public static IServiceCollection AddSingleton( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType!!) + this IServiceCollection services, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + return services.AddSingleton(serviceType, serviceType); } @@ -330,9 +385,11 @@ public static IServiceCollection AddSingleton( /// The to add the service to. /// A reference to this instance after the operation has completed. /// - public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services!!) + public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class { + ThrowHelper.ThrowIfNull(services); + return services.AddSingleton(typeof(TService)); } @@ -347,10 +404,13 @@ public static IServiceCollection AddSingleton( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - Func implementationFactory!!) + this IServiceCollection services, + Func implementationFactory) where TService : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationFactory); + return services.AddSingleton(typeof(TService), implementationFactory); } @@ -367,11 +427,14 @@ public static IServiceCollection AddSingleton( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - Func implementationFactory!!) + this IServiceCollection services, + Func implementationFactory) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationFactory); + return services.AddSingleton(typeof(TService), implementationFactory); } @@ -386,10 +449,14 @@ public static IServiceCollection AddSingleton( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - Type serviceType!!, - object implementationInstance!!) + this IServiceCollection services, + Type serviceType, + object implementationInstance) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationInstance); + var serviceDescriptor = new ServiceDescriptor(serviceType, implementationInstance); services.Add(serviceDescriptor); return services; @@ -405,10 +472,13 @@ public static IServiceCollection AddSingleton( /// A reference to this instance after the operation has completed. /// public static IServiceCollection AddSingleton( - this IServiceCollection services!!, - TService implementationInstance!!) + this IServiceCollection services, + TService implementationInstance) where TService : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(implementationInstance); + return services.AddSingleton(typeof(TService), implementationInstance); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs index 4c98834539fe62..cf75d6998a6947 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs @@ -20,11 +20,14 @@ public class ServiceDescriptor /// The implementing the service. /// The of the service. public ServiceDescriptor( - Type serviceType!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!, + Type serviceType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime) : this(serviceType, lifetime) { + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationType); + ImplementationType = implementationType; } @@ -35,10 +38,13 @@ public ServiceDescriptor( /// The of the service. /// The instance implementing the service. public ServiceDescriptor( - Type serviceType!!, - object instance!!) + Type serviceType, + object instance) : this(serviceType, ServiceLifetime.Singleton) { + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(instance); + ImplementationInstance = instance; } @@ -49,11 +55,14 @@ public ServiceDescriptor( /// A factory used for creating service instances. /// The of the service. public ServiceDescriptor( - Type serviceType!!, - Func factory!!, + Type serviceType, + Func factory, ServiceLifetime lifetime) : this(serviceType, lifetime) { + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(factory); + ImplementationFactory = factory; } @@ -139,9 +148,12 @@ internal Type GetImplementationType() /// The type of the implementation. /// A new instance of . public static ServiceDescriptor Transient( - Type service!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + Type service, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationType); + return Describe(service, implementationType, ServiceLifetime.Transient); } @@ -156,10 +168,12 @@ public static ServiceDescriptor Transient( /// A factory to create new instances of the service implementation. /// A new instance of . public static ServiceDescriptor Transient( - Func implementationFactory!!) + Func implementationFactory) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } @@ -171,9 +185,11 @@ public static ServiceDescriptor Transient( /// The type of the service. /// A factory to create new instances of the service implementation. /// A new instance of . - public static ServiceDescriptor Transient(Func implementationFactory!!) + public static ServiceDescriptor Transient(Func implementationFactory) where TService : class { + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } @@ -185,8 +201,11 @@ public static ServiceDescriptor Transient(FuncThe type of the service. /// A factory to create new instances of the service implementation. /// A new instance of . - public static ServiceDescriptor Transient(Type service!!, Func implementationFactory!!) + public static ServiceDescriptor Transient(Type service, Func implementationFactory) { + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(service, implementationFactory, ServiceLifetime.Transient); } @@ -231,10 +250,12 @@ public static ServiceDescriptor Scoped( /// A factory to create new instances of the service implementation. /// A new instance of . public static ServiceDescriptor Scoped( - Func implementationFactory!!) + Func implementationFactory) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } @@ -246,9 +267,11 @@ public static ServiceDescriptor Scoped( /// The type of the service. /// A factory to create new instances of the service implementation. /// A new instance of . - public static ServiceDescriptor Scoped(Func implementationFactory!!) + public static ServiceDescriptor Scoped(Func implementationFactory) where TService : class { + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } @@ -260,8 +283,11 @@ public static ServiceDescriptor Scoped(FuncThe type of the service. /// A factory to create new instances of the service implementation. /// A new instance of . - public static ServiceDescriptor Scoped(Type service!!, Func implementationFactory!!) + public static ServiceDescriptor Scoped(Type service, Func implementationFactory) { + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(service, implementationFactory, ServiceLifetime.Scoped); } @@ -289,9 +315,12 @@ public static ServiceDescriptor Scoped(Type service!!, FuncThe type of the implementation. /// A new instance of . public static ServiceDescriptor Singleton( - Type service!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType!!) + Type service, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType) { + ThrowHelper.ThrowIfNull(service); + ThrowHelper.ThrowIfNull(implementationType); + return Describe(service, implementationType, ServiceLifetime.Singleton); } @@ -306,10 +335,12 @@ public static ServiceDescriptor Singleton( /// A factory to create new instances of the service implementation. /// A new instance of . public static ServiceDescriptor Singleton( - Func implementationFactory!!) + Func implementationFactory) where TService : class where TImplementation : class, TService { + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } @@ -321,9 +352,11 @@ public static ServiceDescriptor Singleton( /// The type of the service. /// A factory to create new instances of the service implementation. /// A new instance of . - public static ServiceDescriptor Singleton(Func implementationFactory!!) + public static ServiceDescriptor Singleton(Func implementationFactory) where TService : class { + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } @@ -336,9 +369,12 @@ public static ServiceDescriptor Singleton(FuncA factory to create new instances of the service implementation. /// A new instance of . public static ServiceDescriptor Singleton( - Type serviceType!!, - Func implementationFactory!!) + Type serviceType, + Func implementationFactory) { + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationFactory); + return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } @@ -350,9 +386,11 @@ public static ServiceDescriptor Singleton( /// The type of the service. /// The instance of the implementation. /// A new instance of . - public static ServiceDescriptor Singleton(TService implementationInstance!!) + public static ServiceDescriptor Singleton(TService implementationInstance) where TService : class { + ThrowHelper.ThrowIfNull(implementationInstance); + return Singleton(typeof(TService), implementationInstance); } @@ -365,9 +403,12 @@ public static ServiceDescriptor Singleton(TService implementationInsta /// The instance of the implementation. /// A new instance of . public static ServiceDescriptor Singleton( - Type serviceType!!, - object implementationInstance!!) + Type serviceType, + object implementationInstance) { + ThrowHelper.ThrowIfNull(serviceType); + ThrowHelper.ThrowIfNull(implementationInstance); + return new ServiceDescriptor(serviceType, implementationInstance); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs index 048c1b0cfe467e..dbeacc1d50a135 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs @@ -18,8 +18,10 @@ public static class ServiceProviderServiceExtensions /// The type of service object to get. /// The to retrieve the service object from. /// A service object of type or null if there is no such service. - public static T? GetService(this IServiceProvider provider!!) + public static T? GetService(this IServiceProvider provider) { + ThrowHelper.ThrowIfNull(provider); + return (T?)provider.GetService(typeof(T)); } @@ -30,8 +32,11 @@ public static class ServiceProviderServiceExtensions /// An object that specifies the type of service object to get. /// A service object of type . /// There is no service of type . - public static object GetRequiredService(this IServiceProvider provider!!, Type serviceType!!) + public static object GetRequiredService(this IServiceProvider provider, Type serviceType) { + ThrowHelper.ThrowIfNull(provider); + ThrowHelper.ThrowIfNull(serviceType); + if (provider is ISupportRequiredService requiredServiceSupportingProvider) { return requiredServiceSupportingProvider.GetRequiredService(serviceType); @@ -53,8 +58,10 @@ public static object GetRequiredService(this IServiceProvider provider!!, Type s /// The to retrieve the service object from. /// A service object of type . /// There is no service of type . - public static T GetRequiredService(this IServiceProvider provider!!) where T : notnull + public static T GetRequiredService(this IServiceProvider provider) where T : notnull { + ThrowHelper.ThrowIfNull(provider); + return (T)provider.GetRequiredService(typeof(T)); } @@ -64,8 +71,10 @@ public static T GetRequiredService(this IServiceProvider provider!!) where T /// The type of service object to get. /// The to retrieve the services from. /// An enumeration of services of type . - public static IEnumerable GetServices(this IServiceProvider provider!!) + public static IEnumerable GetServices(this IServiceProvider provider) { + ThrowHelper.ThrowIfNull(provider); + return provider.GetRequiredService>(); } @@ -75,8 +84,11 @@ public static IEnumerable GetServices(this IServiceProvider provider!!) /// The to retrieve the services from. /// An object that specifies the type of service object to get. /// An enumeration of services of type . - public static IEnumerable GetServices(this IServiceProvider provider!!, Type serviceType!!) + public static IEnumerable GetServices(this IServiceProvider provider, Type serviceType) { + ThrowHelper.ThrowIfNull(provider); + ThrowHelper.ThrowIfNull(serviceType); + Type? genericEnumerable = typeof(IEnumerable<>).MakeGenericType(serviceType); return (IEnumerable)provider.GetRequiredService(genericEnumerable); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs index 67c641096a420a..7fe53e3aa8551d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs @@ -26,9 +26,9 @@ public DefaultServiceProviderFactory() : this(ServiceProviderOptions.Default) /// with the specified . /// /// The options to use for this instance. - public DefaultServiceProviderFactory(ServiceProviderOptions options!!) + public DefaultServiceProviderFactory(ServiceProviderOptions options) { - _options = options; + _options = options ?? throw new ArgumentNullException(nameof(options)); } /// diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs index 2a4b1c2f0dd401..c18f164cbb77bf 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs @@ -46,8 +46,17 @@ public static ServiceProvider BuildServiceProvider(this IServiceCollection servi /// Configures various service provider behaviors. /// /// The . - public static ServiceProvider BuildServiceProvider(this IServiceCollection services!!, ServiceProviderOptions options!!) + public static ServiceProvider BuildServiceProvider(this IServiceCollection services, ServiceProviderOptions options) { + if (services is null) + { + throw new ArgumentNullException(nameof(services)); + } + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + return new ServiceProvider(services, options); } } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs index 01ee4cc86cbf78..81add91190dae8 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs @@ -529,8 +529,13 @@ public void Add(Type type, ServiceCallSite serviceCallSite) _callSiteCache[new ServiceCacheKey(type, DefaultSlot)] = serviceCallSite; } - public bool IsService(Type serviceType!!) + public bool IsService(Type serviceType) { + if (serviceType is null) + { + throw new ArgumentNullException(nameof(serviceType)); + } + // Querying for an open generic should return false (they aren't resolvable) if (serviceType.IsGenericTypeDefinition) { diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs index 851b90a8a011ee..8071c67013352d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ConstantCallSite.cs @@ -10,9 +10,9 @@ internal sealed class ConstantCallSite : ServiceCallSite private readonly Type _serviceType; internal object? DefaultValue => Value; - public ConstantCallSite(Type serviceType!!, object? defaultValue): base(ResultCache.None) + public ConstantCallSite(Type serviceType, object? defaultValue): base(ResultCache.None) { - _serviceType = serviceType; + _serviceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType)); if (defaultValue != null && !serviceType.IsInstanceOfType(defaultValue)) { throw new ArgumentException(SR.Format(SR.ConstantCantBeConvertedToServiceType, defaultValue.GetType(), serviceType)); diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs index 8785e36d6849e1..6504c362247514 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs @@ -25,13 +25,15 @@ public CompilationLibrary(string type, string name, string version, string? hash, - IEnumerable assemblies!!, + IEnumerable assemblies, IEnumerable dependencies, bool serviceable, string? path, string? hashPath) : base(type, name, version, hash, dependencies, serviceable, path, hashPath) { + ThrowHelper.ThrowIfNull(assemblies); + Assemblies = assemblies.ToArray(); } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs index 2ac677537aceef..a92c5f568ac438 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationOptions.cs @@ -47,7 +47,7 @@ public class CompilationOptions emitEntryPoint: null, generateXmlDocumentation: null); - public CompilationOptions(IEnumerable defines!!, + public CompilationOptions(IEnumerable defines, string? languageVersion, string? platform, bool? allowUnsafe, @@ -60,6 +60,8 @@ public CompilationOptions(IEnumerable defines!!, bool? emitEntryPoint, bool? generateXmlDocumentation) { + ThrowHelper.ThrowIfNull(defines); + Defines = defines.ToArray(); LanguageVersion = languageVersion; Platform = platform; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs index 9eff25c3064dad..48ed7493123a5c 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs @@ -16,12 +16,18 @@ public class DependencyContext Justification = "The annotation should be on the static constructor but is Compiler Generated, annotating the caller Default method instead")] private static readonly Lazy _defaultContext = new(LoadDefault); - public DependencyContext(TargetInfo target!!, - CompilationOptions compilationOptions!!, - IEnumerable compileLibraries!!, - IEnumerable runtimeLibraries!!, - IEnumerable runtimeGraph!!) + public DependencyContext(TargetInfo target, + CompilationOptions compilationOptions, + IEnumerable compileLibraries, + IEnumerable runtimeLibraries, + IEnumerable runtimeGraph) { + ThrowHelper.ThrowIfNull(target); + ThrowHelper.ThrowIfNull(compilationOptions); + ThrowHelper.ThrowIfNull(compileLibraries); + ThrowHelper.ThrowIfNull(runtimeLibraries); + ThrowHelper.ThrowIfNull(runtimeGraph); + Target = target; CompilationOptions = compilationOptions; CompileLibraries = compileLibraries.ToArray(); @@ -42,8 +48,10 @@ public DependencyContext(TargetInfo target!!, public IReadOnlyList RuntimeGraph { get; } - public DependencyContext Merge(DependencyContext other!!) + public DependencyContext Merge(DependencyContext other) { + ThrowHelper.ThrowIfNull(other); + return new DependencyContext( Target, CompilationOptions, diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs index 6b77fd4ec34a54..a40f12ecbebec5 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs @@ -13,63 +13,97 @@ public static class DependencyContextExtensions { private const string NativeImageSufix = ".ni"; - public static IEnumerable GetDefaultNativeAssets(this DependencyContext self!!) + public static IEnumerable GetDefaultNativeAssets(this DependencyContext self) { + ThrowHelper.ThrowIfNull(self); + return self.RuntimeLibraries.SelectMany(library => library.GetDefaultNativeAssets(self)); } - public static IEnumerable GetDefaultNativeRuntimeFileAssets(this DependencyContext self!!) + public static IEnumerable GetDefaultNativeRuntimeFileAssets(this DependencyContext self) { + ThrowHelper.ThrowIfNull(self); + return self.RuntimeLibraries.SelectMany(library => library.GetDefaultNativeRuntimeFileAssets(self)); } - public static IEnumerable GetRuntimeNativeAssets(this DependencyContext self!!, string runtimeIdentifier!!) + public static IEnumerable GetRuntimeNativeAssets(this DependencyContext self, string runtimeIdentifier) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(runtimeIdentifier); + return self.RuntimeLibraries.SelectMany(library => library.GetRuntimeNativeAssets(self, runtimeIdentifier)); } - public static IEnumerable GetRuntimeNativeRuntimeFileAssets(this DependencyContext self!!, string runtimeIdentifier!!) + public static IEnumerable GetRuntimeNativeRuntimeFileAssets(this DependencyContext self, string runtimeIdentifier) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(runtimeIdentifier); + return self.RuntimeLibraries.SelectMany(library => library.GetRuntimeNativeRuntimeFileAssets(self, runtimeIdentifier)); } - public static IEnumerable GetDefaultNativeAssets(this RuntimeLibrary self!!, DependencyContext context) + public static IEnumerable GetDefaultNativeAssets(this RuntimeLibrary self, DependencyContext context) { + ThrowHelper.ThrowIfNull(self); + return ResolveAssets(context, string.Empty, self.NativeLibraryGroups); } - public static IEnumerable GetDefaultNativeRuntimeFileAssets(this RuntimeLibrary self!!, DependencyContext context) + public static IEnumerable GetDefaultNativeRuntimeFileAssets(this RuntimeLibrary self, DependencyContext context) { + ThrowHelper.ThrowIfNull(self); + return ResolveRuntimeFiles(context, string.Empty, self.NativeLibraryGroups); } - public static IEnumerable GetRuntimeNativeAssets(this RuntimeLibrary self!!, DependencyContext context!!, string runtimeIdentifier!!) + public static IEnumerable GetRuntimeNativeAssets(this RuntimeLibrary self, DependencyContext context, string runtimeIdentifier) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(context); + ThrowHelper.ThrowIfNull(runtimeIdentifier); + return ResolveAssets(context, runtimeIdentifier, self.NativeLibraryGroups); } - public static IEnumerable GetRuntimeNativeRuntimeFileAssets(this RuntimeLibrary self!!, DependencyContext context!!, string runtimeIdentifier!!) + public static IEnumerable GetRuntimeNativeRuntimeFileAssets(this RuntimeLibrary self, DependencyContext context, string runtimeIdentifier) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(context); + ThrowHelper.ThrowIfNull(runtimeIdentifier); + return ResolveRuntimeFiles(context, runtimeIdentifier, self.NativeLibraryGroups); } - public static IEnumerable GetDefaultAssemblyNames(this DependencyContext self!!) + public static IEnumerable GetDefaultAssemblyNames(this DependencyContext self) { + ThrowHelper.ThrowIfNull(self); + return self.RuntimeLibraries.SelectMany(library => library.GetDefaultAssemblyNames(self)); } - public static IEnumerable GetRuntimeAssemblyNames(this DependencyContext self!!, string runtimeIdentifier!!) + public static IEnumerable GetRuntimeAssemblyNames(this DependencyContext self, string runtimeIdentifier) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(runtimeIdentifier); + return self.RuntimeLibraries.SelectMany(library => library.GetRuntimeAssemblyNames(self, runtimeIdentifier)); } - public static IEnumerable GetDefaultAssemblyNames(this RuntimeLibrary self!!, DependencyContext context!!) + public static IEnumerable GetDefaultAssemblyNames(this RuntimeLibrary self, DependencyContext context) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(context); + return ResolveAssets(context, string.Empty, self.RuntimeAssemblyGroups).Select(GetAssemblyName); } - public static IEnumerable GetRuntimeAssemblyNames(this RuntimeLibrary self!!, DependencyContext context!!, string runtimeIdentifier!!) + public static IEnumerable GetRuntimeAssemblyNames(this RuntimeLibrary self, DependencyContext context, string runtimeIdentifier) { + ThrowHelper.ThrowIfNull(self); + ThrowHelper.ThrowIfNull(context); + ThrowHelper.ThrowIfNull(runtimeIdentifier); + return ResolveAssets(context, runtimeIdentifier, self.RuntimeAssemblyGroups).Select(GetAssemblyName); } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs index fb3e4faeccf70d..47ab61c923179c 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs @@ -19,8 +19,10 @@ public class DependencyContextJsonReader : IDependencyContextReader private readonly IDictionary _stringPool = new Dictionary(); - public DependencyContext Read(Stream stream!!) + public DependencyContext Read(Stream stream) { + ThrowHelper.ThrowIfNull(stream); + ArraySegment buffer = ReadToEnd(stream); try { diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs index 087db03c039afa..6bcdd35004c7c2 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs @@ -52,8 +52,10 @@ private static bool IsEntryAssembly(Assembly assembly) } [RequiresAssemblyFiles("DependencyContext for an assembly from a application published as single-file is not supported. The method will return null. Make sure the calling code can handle this case.")] - public DependencyContext? Load(Assembly assembly!!) + public DependencyContext? Load(Assembly assembly) { + ThrowHelper.ThrowIfNull(assembly); + DependencyContext? context = null; using (IDependencyContextReader reader = _jsonReaderFactory()) { diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs index 96e8896ede6f55..9005306cebfb28 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs @@ -13,8 +13,11 @@ namespace Microsoft.Extensions.DependencyModel { public class DependencyContextWriter { - public void Write(DependencyContext context!!, Stream stream!!) + public void Write(DependencyContext context, Stream stream) { + ThrowHelper.ThrowIfNull(context); + ThrowHelper.ThrowIfNull(stream); + // Custom encoder is required to fix https://github.com/dotnet/core-setup/issues/7137 // Since the JSON is only written to a file that is read by the SDK (and not transmitted over the wire), // it is safe to skip escaping certain characters in this scenario diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs index ffdfa8032e8b0b..65852d4183584d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs @@ -52,10 +52,8 @@ public Library(string type, { throw new ArgumentException(null, nameof(version)); } - if (dependencies == null) - { - throw new ArgumentNullException(nameof(dependencies)); - } + ThrowHelper.ThrowIfNull(dependencies); + Type = type; Name = name; Version = version; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj b/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj index d7af4c0bd0bbf5..39dc8df474c242 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj @@ -15,6 +15,8 @@ Microsoft.Extensions.DependencyModel.DependencyContext + diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs index c190e658b6fc95..bec2afa8c79e90 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs @@ -30,15 +30,21 @@ internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem) { } - internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem!!, string basePath!!, DependencyContextPaths dependencyContextPaths!!) + internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem, string basePath, DependencyContextPaths dependencyContextPaths) { + ThrowHelper.ThrowIfNull(fileSystem); + ThrowHelper.ThrowIfNull(basePath); + ThrowHelper.ThrowIfNull(dependencyContextPaths); + _fileSystem = fileSystem; _basePath = basePath; _dependencyContextPaths = dependencyContextPaths; } - public bool TryResolveAssemblyPaths(CompilationLibrary library!!, List? assemblies) + public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) { + ThrowHelper.ThrowIfNull(library); + bool isProject = string.Equals(library.Type, "project", StringComparison.OrdinalIgnoreCase) || string.Equals(library.Type, "msbuildproject", StringComparison.OrdinalIgnoreCase); diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs index 469afe37fd2022..224041317d7f3b 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs @@ -10,8 +10,10 @@ public class CompositeCompilationAssemblyResolver: ICompilationAssemblyResolver { private readonly ICompilationAssemblyResolver[] _resolvers; - public CompositeCompilationAssemblyResolver(ICompilationAssemblyResolver[] resolvers!!) + public CompositeCompilationAssemblyResolver(ICompilationAssemblyResolver[] resolvers) { + ThrowHelper.ThrowIfNull(resolvers); + _resolvers = resolvers; } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs index b7966379e2b336..48ea69ee67ee76 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs @@ -29,8 +29,11 @@ internal PackageCompilationAssemblyResolver(IEnvironment environment, { } - internal PackageCompilationAssemblyResolver(IFileSystem fileSystem!!, string[] nugetPackageDirectories!!) + internal PackageCompilationAssemblyResolver(IFileSystem fileSystem, string[] nugetPackageDirectories) { + ThrowHelper.ThrowIfNull(fileSystem); + ThrowHelper.ThrowIfNull(nugetPackageDirectories); + _fileSystem = fileSystem; _nugetPackageDirectories = nugetPackageDirectories; } @@ -71,8 +74,10 @@ internal static string[] GetDefaultProbeDirectories(IEnvironment environment) return new string[] { Path.Combine(basePath, ".nuget", "packages") }; } - public bool TryResolveAssemblyPaths(CompilationLibrary library!!, List? assemblies) + public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) { + ThrowHelper.ThrowIfNull(library); + if (_nugetPackageDirectories == null || _nugetPackageDirectories.Length == 0 || !string.Equals(library.Type, "package", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs index c1e04a419e0937..a0357b604af906 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs @@ -31,15 +31,20 @@ internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, IEnvironment envi { } - internal ReferenceAssemblyPathResolver(IFileSystem fileSystem!!, string? defaultReferenceAssembliesPath, string[] fallbackSearchPaths!!) + internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, string? defaultReferenceAssembliesPath, string[] fallbackSearchPaths) { + ThrowHelper.ThrowIfNull(fileSystem); + ThrowHelper.ThrowIfNull(fallbackSearchPaths); + _fileSystem = fileSystem; _defaultReferenceAssembliesPath = defaultReferenceAssembliesPath; _fallbackSearchPaths = fallbackSearchPaths; } - public bool TryResolveAssemblyPaths(CompilationLibrary library!!, List? assemblies) + public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) { + ThrowHelper.ThrowIfNull(library); + if (!string.Equals(library.Type, "referenceassembly", StringComparison.OrdinalIgnoreCase)) { return false; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs index bb153401a3a9ae..bb9b5cb599de23 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs @@ -19,10 +19,8 @@ public RuntimeFallbacks(string runtime, IEnumerable fallbacks) { throw new ArgumentException(null, nameof(runtime)); } - if (fallbacks == null) - { - throw new ArgumentNullException(nameof(fallbacks)); - } + ThrowHelper.ThrowIfNull(fallbacks); + Runtime = runtime; Fallbacks = fallbacks.ToArray(); } diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs index 74e97f2895729f..1403ef4d88651d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs @@ -87,9 +87,9 @@ public RuntimeLibrary(string type, string name, string version, string? hash, - IReadOnlyList runtimeAssemblyGroups!!, - IReadOnlyList nativeLibraryGroups!!, - IEnumerable resourceAssemblies!!, + IReadOnlyList runtimeAssemblyGroups, + IReadOnlyList nativeLibraryGroups, + IEnumerable resourceAssemblies, IEnumerable dependencies, bool serviceable, string? path, @@ -105,6 +105,10 @@ public RuntimeLibrary(string type, hashPath, runtimeStoreManifestName) { + ThrowHelper.ThrowIfNull(runtimeAssemblyGroups); + ThrowHelper.ThrowIfNull(nativeLibraryGroups); + ThrowHelper.ThrowIfNull(resourceAssemblies); + RuntimeAssemblyGroups = runtimeAssemblyGroups; ResourceAssemblies = resourceAssemblies.ToArray(); NativeLibraryGroups = nativeLibraryGroups; diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs index 35102cd399bb4f..5fb6d9c25527f4 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs @@ -26,8 +26,10 @@ public class CompositeDirectoryContents : IDirectoryContents /// /// The list of for which the results have to be composed. /// The path. - public CompositeDirectoryContents(IList fileProviders!!, string subpath) + public CompositeDirectoryContents(IList fileProviders, string subpath) { + ThrowHelper.ThrowIfNull(fileProviders); + _fileProviders = fileProviders; _subPath = subpath; } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs index d6070def58cca9..1343ab4bbe45fd 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs @@ -29,8 +29,10 @@ public CompositeFileProvider(params IFileProvider[]? fileProviders) /// Initializes a new instance of the class using a collection of file provider. /// /// The collection of - public CompositeFileProvider(IEnumerable fileProviders!!) + public CompositeFileProvider(IEnumerable fileProviders) { + ThrowHelper.ThrowIfNull(fileProviders); + _fileProviders = fileProviders.ToArray(); } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj index 68c52aeb7f2e2f..936b8f0450ee0b 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/Microsoft.Extensions.FileProviders.Composite.csproj @@ -14,6 +14,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs index b78b9f5bb78044..68a0b4cf9590d7 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs @@ -33,8 +33,10 @@ public PhysicalDirectoryContents(string directory) /// /// The directory /// Specifies which files or directories are excluded from enumeration. - public PhysicalDirectoryContents(string directory!!, ExclusionFilters filters) + public PhysicalDirectoryContents(string directory, ExclusionFilters filters) { + ThrowHelper.ThrowIfNull(directory); + _directory = directory; _filters = filters; } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj index 18ccacdf36cd42..f583d482845258 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Microsoft.Extensions.FileProviders.Physical.csproj @@ -15,6 +15,8 @@ Link="Common\src\Extensions\EmptyDisposable.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs index 9e99d2576c2c07..89d9bf7eadce0e 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs @@ -131,8 +131,10 @@ public PhysicalFilesWatcher( /// A globbing pattern for files and directories to watch /// A change token for all files that match the filter /// When is null - public IChangeToken CreateFileChangeToken(string filter!!) + public IChangeToken CreateFileChangeToken(string filter) { + ThrowHelper.ThrowIfNull(filter); + filter = NormalizePath(filter); // Absolute paths and paths traversing above root not permitted. diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs index e02eb2da05374a..5b464a2791dc64 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs @@ -17,8 +17,10 @@ public class FileInfoWrapper : FileInfoBase /// Initializes instance of to wrap the specified object . /// /// The - public FileInfoWrapper(FileInfo fileInfo!!) + public FileInfoWrapper(FileInfo fileInfo) { + ThrowHelper.ThrowIfNull(fileInfo); + _fileInfo = fileInfo; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs index 9e8e1416e41d37..b643e970b2d835 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs @@ -35,8 +35,10 @@ public struct FilePatternMatch : IEquatable /// /// The path to the file matched, relative to the beginning of the matching search pattern. /// The subpath to the file matched, relative to the first wildcard in the matching search pattern. - public FilePatternMatch(string path!!, string? stem) + public FilePatternMatch(string path, string? stem) { + ThrowHelper.ThrowIfNull(path); + Path = path; Stem = stem; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs index 490c5bec25354a..53d71cda8ee12e 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs @@ -13,8 +13,10 @@ public class LiteralPathSegment : IPathSegment public bool CanProduceStem => false; - public LiteralPathSegment(string value!!, StringComparison comparisonType) + public LiteralPathSegment(string value, StringComparison comparisonType) { + ThrowHelper.ThrowIfNull(value); + Value = value; _comparisonType = comparisonType; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs index 5f925b2d83f9b5..8df0bd4ffe51c0 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs @@ -15,8 +15,12 @@ public class WildcardPathSegment : IPathSegment private readonly StringComparison _comparisonType; - public WildcardPathSegment(string beginsWith!!, List contains!!, string endsWith!!, StringComparison comparisonType) + public WildcardPathSegment(string beginsWith, List contains, string endsWith, StringComparison comparisonType) { + ThrowHelper.ThrowIfNull(beginsWith); + ThrowHelper.ThrowIfNull(contains); + ThrowHelper.ThrowIfNull(endsWith); + BeginsWith = beginsWith; Contains = contains; EndsWith = endsWith; diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs index de726bbb7793c8..070ed6cac80be3 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs @@ -10,8 +10,10 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts public abstract class PatternContextLinear : PatternContext { - public PatternContextLinear(ILinearPattern pattern!!) + public PatternContextLinear(ILinearPattern pattern) { + ThrowHelper.ThrowIfNull(pattern); + Pattern = pattern; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs index bbce5625337db3..2927530981686a 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs @@ -9,8 +9,10 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts { public abstract class PatternContextRagged : PatternContext { - public PatternContextRagged(IRaggedPattern pattern!!) + public PatternContextRagged(IRaggedPattern pattern) { + ThrowHelper.ThrowIfNull(pattern); + Pattern = pattern; } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs index f519150c450411..1800f36cb24f3f 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs @@ -25,8 +25,10 @@ public PatternBuilder(StringComparison comparisonType) public StringComparison ComparisonType { get; } - public IPattern Build(string pattern!!) + public IPattern Build(string pattern) { + ThrowHelper.ThrowIfNull(pattern); + pattern = pattern.TrimStart(_slashes); if (pattern.TrimEnd(_slashes).Length < pattern.Length) diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Matcher.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Matcher.cs index f298d001f8906e..56311ba91506ac 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Matcher.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Matcher.cs @@ -160,8 +160,10 @@ public virtual Matcher AddExclude(string pattern) /// /// The root directory for the search /// Always returns instance of , even if no files were matched - public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo!!) + public virtual PatternMatchingResult Execute(DirectoryInfoBase directoryInfo) { + ThrowHelper.ThrowIfNull(directoryInfo); + var context = new MatcherContext(_includePatterns, _excludePatterns, directoryInfo, _comparison); return context.Execute(); } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs index 4c2ab4ac04e9de..c400b6a665e90b 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs @@ -98,8 +98,10 @@ public static PatternMatchingResult Match(this Matcher matcher, IEnumerableThe root directory for the matcher to match the files from. /// The files to run the matcher against. /// The match results. - public static PatternMatchingResult Match(this Matcher matcher!!, string rootDir, IEnumerable? files) + public static PatternMatchingResult Match(this Matcher matcher, string rootDir, IEnumerable? files) { + ThrowHelper.ThrowIfNull(matcher); + return matcher.Execute(new InMemoryDirectoryInfo(rootDir, files)); } } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj index 7e4f494e6daa36..0efcaaf43c25b0 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Microsoft.Extensions.FileSystemGlobbing.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) @@ -13,6 +13,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs index e0536ece0c315d..84ae35003e117a 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs @@ -27,8 +27,10 @@ public PatternMatchingResult(IEnumerable files) /// /// A collection of /// A value that determines if has any matches. - public PatternMatchingResult(IEnumerable files!!, bool hasMatches) + public PatternMatchingResult(IEnumerable files, bool hasMatches) { + ThrowHelper.ThrowIfNull(files); + Files = files; HasMatches = hasMatches; } diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs index 6a8d228947c3aa..10d05076102bfa 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration; @@ -11,8 +12,10 @@ namespace Microsoft.Extensions.Hosting /// public class HostBuilderContext { - public HostBuilderContext(IDictionary properties!!) + public HostBuilderContext(IDictionary properties) { + ThrowHelper.ThrowIfNull(properties); + Properties = properties; } diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs index e722f2ddb812be..811b8d4dc677c4 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs @@ -15,8 +15,10 @@ public static class HostEnvironmentEnvExtensions /// /// An instance of . /// True if the environment name is , otherwise false. - public static bool IsDevelopment(this IHostEnvironment hostEnvironment!!) + public static bool IsDevelopment(this IHostEnvironment hostEnvironment) { + ThrowHelper.ThrowIfNull(hostEnvironment); + return hostEnvironment.IsEnvironment(Environments.Development); } @@ -25,8 +27,10 @@ public static bool IsDevelopment(this IHostEnvironment hostEnvironment!!) /// /// An instance of . /// True if the environment name is , otherwise false. - public static bool IsStaging(this IHostEnvironment hostEnvironment!!) + public static bool IsStaging(this IHostEnvironment hostEnvironment) { + ThrowHelper.ThrowIfNull(hostEnvironment); + return hostEnvironment.IsEnvironment(Environments.Staging); } @@ -35,8 +39,10 @@ public static bool IsStaging(this IHostEnvironment hostEnvironment!!) /// /// An instance of . /// True if the environment name is , otherwise false. - public static bool IsProduction(this IHostEnvironment hostEnvironment!!) + public static bool IsProduction(this IHostEnvironment hostEnvironment) { + ThrowHelper.ThrowIfNull(hostEnvironment); + return hostEnvironment.IsEnvironment(Environments.Production); } @@ -47,9 +53,11 @@ public static bool IsProduction(this IHostEnvironment hostEnvironment!!) /// Environment name to validate against. /// True if the specified name is the same as the current environment, otherwise false. public static bool IsEnvironment( - this IHostEnvironment hostEnvironment!!, + this IHostEnvironment hostEnvironment, string environmentName) { + ThrowHelper.ThrowIfNull(hostEnvironment); + return string.Equals( hostEnvironment.EnvironmentName, environmentName, diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs index 8871b3d20cb1bb..3f91b8faa960f8 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs @@ -16,8 +16,10 @@ public static class HostingEnvironmentExtensions /// /// An instance of . /// True if the environment name is , otherwise false. - public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment!!) + public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment) { + ThrowHelper.ThrowIfNull(hostingEnvironment); + return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } @@ -26,8 +28,10 @@ public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment!!) /// /// An instance of . /// True if the environment name is , otherwise false. - public static bool IsStaging(this IHostingEnvironment hostingEnvironment!!) + public static bool IsStaging(this IHostingEnvironment hostingEnvironment) { + ThrowHelper.ThrowIfNull(hostingEnvironment); + return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } @@ -36,8 +40,10 @@ public static bool IsStaging(this IHostingEnvironment hostingEnvironment!!) /// /// An instance of . /// True if the environment name is , otherwise false. - public static bool IsProduction(this IHostingEnvironment hostingEnvironment!!) + public static bool IsProduction(this IHostingEnvironment hostingEnvironment) { + ThrowHelper.ThrowIfNull(hostingEnvironment); + return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } @@ -48,9 +54,11 @@ public static bool IsProduction(this IHostingEnvironment hostingEnvironment!!) /// Environment name to validate against. /// True if the specified name is the same as the current environment, otherwise false. public static bool IsEnvironment( - this IHostingEnvironment hostingEnvironment!!, + this IHostingEnvironment hostingEnvironment, string environmentName) { + ThrowHelper.ThrowIfNull(hostingEnvironment); + return string.Equals( hostingEnvironment.EnvironmentName, environmentName, diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj index 32a553ddab2740..9e306ec76a050c 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj @@ -17,6 +17,7 @@ + diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj index 042bf76144d8c2..4daa7499d5927c 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj @@ -9,6 +9,7 @@ false true true + annotations @@ -22,6 +23,7 @@ + diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs index 5767ba2a769c03..17270278e6f113 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/ServiceState.cs @@ -26,8 +26,10 @@ public struct ServiceState /// /// Create custom ServiceState. /// - public ServiceState(string state!!) + public ServiceState(string state) { + ThrowHelper.ThrowIfNull(state); + _data = Encoding.UTF8.GetBytes(state); } diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs index e49b00fd49c0e9..ae1ce1e903f0a5 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs @@ -19,8 +19,12 @@ public partial class SystemdLifetime : IHostLifetime, IDisposable private CancellationTokenRegistration _applicationStartedRegistration; private CancellationTokenRegistration _applicationStoppingRegistration; - public SystemdLifetime(IHostEnvironment environment!!, IHostApplicationLifetime applicationLifetime!!, ISystemdNotifier systemdNotifier!!, ILoggerFactory loggerFactory) + public SystemdLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ISystemdNotifier systemdNotifier, ILoggerFactory loggerFactory) { + ThrowHelper.ThrowIfNull(environment); + ThrowHelper.ThrowIfNull(applicationLifetime); + ThrowHelper.ThrowIfNull(systemdNotifier); + Environment = environment; ApplicationLifetime = applicationLifetime; SystemdNotifier = systemdNotifier; diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj index 6e9ac5eb13bcdf..7197844b55a612 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj @@ -24,6 +24,8 @@ Link="Common\Interop\Windows\Kernel32\Interop.CreateToolhelp32Snapshot.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs index 650746333f40e8..b535f51f2beef8 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/WindowsServiceLifetime.cs @@ -23,8 +23,13 @@ public WindowsServiceLifetime(IHostEnvironment environment, IHostApplicationLife { } - public WindowsServiceLifetime(IHostEnvironment environment!!, IHostApplicationLifetime applicationLifetime!!, ILoggerFactory loggerFactory, IOptions optionsAccessor!!, IOptions windowsServiceOptionsAccessor!!) + public WindowsServiceLifetime(IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, ILoggerFactory loggerFactory, IOptions optionsAccessor, IOptions windowsServiceOptionsAccessor) { + ThrowHelper.ThrowIfNull(environment); + ThrowHelper.ThrowIfNull(applicationLifetime); + ThrowHelper.ThrowIfNull(optionsAccessor); + ThrowHelper.ThrowIfNull(windowsServiceOptionsAccessor); + Environment = environment; ApplicationLifetime = applicationLifetime; Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs index db2bbc0709086f..bcc7963d28476a 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostApplicationBuilder.cs @@ -321,40 +321,50 @@ public void ApplyChanges() public IHostBuilder ConfigureHostConfiguration(Action configureDelegate) { - _configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); + ThrowHelper.ThrowIfNull(configureDelegate); + + _configureHostConfigActions.Add(configureDelegate); return this; } public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) { - _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); + ThrowHelper.ThrowIfNull(configureDelegate); + + _configureAppConfigActions.Add(configureDelegate); return this; } public IHostBuilder ConfigureServices(Action configureDelegate) { - _configureServicesActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); + ThrowHelper.ThrowIfNull(configureDelegate); + + _configureServicesActions.Add(configureDelegate); return this; } public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory) where TContainerBuilder : notnull { - _serviceProviderFactory = new ServiceFactoryAdapter(factory ?? throw new ArgumentNullException(nameof(factory))); + ThrowHelper.ThrowIfNull(factory); + + _serviceProviderFactory = new ServiceFactoryAdapter(factory); return this; } public IHostBuilder UseServiceProviderFactory(Func> factory) where TContainerBuilder : notnull { - _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostApplicationBuilder._hostBuilderContext, factory ?? throw new ArgumentNullException(nameof(factory))); + ThrowHelper.ThrowIfNull(factory); + + _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostApplicationBuilder._hostBuilderContext, factory); return this; } public IHostBuilder ConfigureContainer(Action configureDelegate) { - _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate - ?? throw new ArgumentNullException(nameof(configureDelegate)))); + ThrowHelper.ThrowIfNull(configureDelegate); + _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate)); return this; } } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs index 0d44714157f1c7..6c283b030041f3 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs @@ -50,8 +50,10 @@ public partial class HostBuilder : IHostBuilder /// The delegate for configuring the that will be used /// to construct the for the host. /// The same instance of the for chaining. - public IHostBuilder ConfigureHostConfiguration(Action configureDelegate!!) + public IHostBuilder ConfigureHostConfiguration(Action configureDelegate) { + ThrowHelper.ThrowIfNull(configureDelegate); + _configureHostConfigActions.Add(configureDelegate); return this; } @@ -64,8 +66,10 @@ public IHostBuilder ConfigureHostConfiguration(Action con /// The delegate for configuring the that will be used /// to construct the for the host. /// The same instance of the for chaining. - public IHostBuilder ConfigureAppConfiguration(Action configureDelegate!!) + public IHostBuilder ConfigureAppConfiguration(Action configureDelegate) { + ThrowHelper.ThrowIfNull(configureDelegate); + _configureAppConfigActions.Add(configureDelegate); return this; } @@ -76,8 +80,10 @@ public IHostBuilder ConfigureAppConfiguration(ActionThe delegate for configuring the that will be used /// to construct the for the host. /// The same instance of the for chaining. - public IHostBuilder ConfigureServices(Action configureDelegate!!) + public IHostBuilder ConfigureServices(Action configureDelegate) { + ThrowHelper.ThrowIfNull(configureDelegate); + _configureServicesActions.Add(configureDelegate); return this; } @@ -88,8 +94,10 @@ public IHostBuilder ConfigureServices(ActionThe type of the builder to create. /// A factory used for creating service providers. /// The same instance of the for chaining. - public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory!!) where TContainerBuilder : notnull + public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory) where TContainerBuilder : notnull { + ThrowHelper.ThrowIfNull(factory); + _serviceProviderFactory = new ServiceFactoryAdapter(factory); return this; } @@ -100,8 +108,10 @@ public IHostBuilder UseServiceProviderFactory(IServiceProvide /// A factory used for creating service providers. /// The type of the builder to create. /// The same instance of the for chaining. - public IHostBuilder UseServiceProviderFactory(Func> factory!!) where TContainerBuilder : notnull + public IHostBuilder UseServiceProviderFactory(Func> factory) where TContainerBuilder : notnull { + ThrowHelper.ThrowIfNull(factory); + _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostBuilderContext!, factory); return this; } @@ -114,8 +124,10 @@ public IHostBuilder UseServiceProviderFactory(FuncThe delegate for configuring the that will be used /// to construct the for the host. /// The same instance of the for chaining. - public IHostBuilder ConfigureContainer(Action configureDelegate!!) + public IHostBuilder ConfigureContainer(Action configureDelegate) { + ThrowHelper.ThrowIfNull(configureDelegate); + _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate)); return this; } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs index 81bea7d6c40c6d..4f68146976d93a 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostingHostBuilderExtensions.cs @@ -31,10 +31,11 @@ public static IHostBuilder UseEnvironment(this IHostBuilder hostBuilder, string { return hostBuilder.ConfigureHostConfiguration(configBuilder => { + ThrowHelper.ThrowIfNull(environment); + configBuilder.AddInMemoryCollection(new[] { - new KeyValuePair(HostDefaults.EnvironmentKey, - environment ?? throw new ArgumentNullException(nameof(environment))) + new KeyValuePair(HostDefaults.EnvironmentKey, environment) }); }); } @@ -50,10 +51,11 @@ public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string { return hostBuilder.ConfigureHostConfiguration(configBuilder => { + ThrowHelper.ThrowIfNull(contentRoot); + configBuilder.AddInMemoryCollection(new[] { - new KeyValuePair(HostDefaults.ContentRootKey, - contentRoot ?? throw new ArgumentNullException(nameof(contentRoot))) + new KeyValuePair(HostDefaults.ContentRootKey, contentRoot) }); }); } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs index a1e8efdaf9447b..810a28ed10b3d7 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs @@ -9,8 +9,10 @@ internal sealed class ConfigureContainerAdapter : IConfigureC { private Action _action; - public ConfigureContainerAdapter(Action action!!) + public ConfigureContainerAdapter(Action action) { + ThrowHelper.ThrowIfNull(action); + _action = action; } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs index fe4821048ef5ec..b4874360aeaa23 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConsoleLifetime.cs @@ -26,12 +26,17 @@ public partial class ConsoleLifetime : IHostLifetime, IDisposable public ConsoleLifetime(IOptions options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions hostOptions) : this(options, environment, applicationLifetime, hostOptions, NullLoggerFactory.Instance) { } - public ConsoleLifetime(IOptions options, IHostEnvironment environment!!, IHostApplicationLifetime applicationLifetime!!, IOptions hostOptions, ILoggerFactory loggerFactory) + public ConsoleLifetime(IOptions options, IHostEnvironment environment, IHostApplicationLifetime applicationLifetime, IOptions hostOptions, ILoggerFactory loggerFactory) { - Options = options?.Value ?? throw new ArgumentNullException(nameof(options)); + ThrowHelper.ThrowIfNull(options?.Value, nameof(options)); + ThrowHelper.ThrowIfNull(applicationLifetime); + ThrowHelper.ThrowIfNull(environment); + ThrowHelper.ThrowIfNull(hostOptions?.Value, nameof(hostOptions)); + + Options = options.Value; Environment = environment; ApplicationLifetime = applicationLifetime; - HostOptions = hostOptions?.Value ?? throw new ArgumentNullException(nameof(hostOptions)); + HostOptions = hostOptions.Value; Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs index 301e2f851f8fc7..f0339b80020968 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs @@ -24,14 +24,19 @@ internal sealed class Host : IHost, IAsyncDisposable private IEnumerable? _hostedServices; private volatile bool _stopCalled; - public Host(IServiceProvider services!!, + public Host(IServiceProvider services, IHostEnvironment hostEnvironment, PhysicalFileProvider defaultProvider, - IHostApplicationLifetime applicationLifetime!!, - ILogger logger!!, - IHostLifetime hostLifetime!!, + IHostApplicationLifetime applicationLifetime, + ILogger logger, + IHostLifetime hostLifetime, IOptions options) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(applicationLifetime); + ThrowHelper.ThrowIfNull(logger); + ThrowHelper.ThrowIfNull(hostLifetime); + Services = services; _applicationLifetime = (applicationLifetime as ApplicationLifetime)!; _hostEnvironment = hostEnvironment; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs index 578a6cf765bf8c..6eebf47ca71aba 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs @@ -13,13 +13,18 @@ internal sealed class ServiceFactoryAdapter : IServiceFactory private readonly Func? _contextResolver; private Func>? _factoryResolver; - public ServiceFactoryAdapter(IServiceProviderFactory serviceProviderFactory!!) + public ServiceFactoryAdapter(IServiceProviderFactory serviceProviderFactory) { + ThrowHelper.ThrowIfNull(serviceProviderFactory); + _serviceProviderFactory = serviceProviderFactory; } - public ServiceFactoryAdapter(Func contextResolver!!, Func> factoryResolver!!) + public ServiceFactoryAdapter(Func contextResolver, Func> factoryResolver) { + ThrowHelper.ThrowIfNull(contextResolver); + ThrowHelper.ThrowIfNull(factoryResolver); + _contextResolver = contextResolver; _factoryResolver = factoryResolver; } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj b/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj index 202fd8c6f4f1ed..77e5a5ba2fd40b 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj @@ -24,6 +24,7 @@ + diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs index a8e8f064fd8463..ca353d313cb6dc 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs @@ -20,9 +20,11 @@ public static class OptionsBuilderExtensions /// The type of options. /// The to configure options instance. /// The so that additional calls can be chained. - public static OptionsBuilder ValidateOnStart<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this OptionsBuilder optionsBuilder!!) + public static OptionsBuilder ValidateOnStart<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] TOptions>(this OptionsBuilder optionsBuilder) where TOptions : class { + ThrowHelper.ThrowIfNull(optionsBuilder); + optionsBuilder.Services.AddHostedService(); optionsBuilder.Services.AddOptions() .Configure>((vo, options) => diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs index dcbf57b7e22b6c..b51f570d872add 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs @@ -59,12 +59,18 @@ internal class DefaultHttpClientFactory : IHttpClientFactory, IHttpMessageHandle private readonly TimerCallback _expiryCallback; public DefaultHttpClientFactory( - IServiceProvider services!!, - IServiceScopeFactory scopeFactory!!, - ILoggerFactory loggerFactory!!, - IOptionsMonitor optionsMonitor!!, - IEnumerable filters!!) + IServiceProvider services, + IServiceScopeFactory scopeFactory, + ILoggerFactory loggerFactory, + IOptionsMonitor optionsMonitor, + IEnumerable filters) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(scopeFactory); + ThrowHelper.ThrowIfNull(loggerFactory); + ThrowHelper.ThrowIfNull(optionsMonitor); + ThrowHelper.ThrowIfNull(filters); + _services = services; _scopeFactory = scopeFactory; _optionsMonitor = optionsMonitor; @@ -89,8 +95,10 @@ public DefaultHttpClientFactory( _cleanupActiveLock = new object(); } - public HttpClient CreateClient(string name!!) + public HttpClient CreateClient(string name) { + ThrowHelper.ThrowIfNull(name); + HttpMessageHandler handler = CreateHandler(name); var client = new HttpClient(handler, disposeHandler: false); @@ -103,8 +111,10 @@ public HttpClient CreateClient(string name!!) return client; } - public HttpMessageHandler CreateHandler(string name!!) + public HttpMessageHandler CreateHandler(string name) { + ThrowHelper.ThrowIfNull(name); + ActiveHandlerTrackingEntry entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value; StartHandlerEntryTimer(entry); diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs index 5fb76dac971aa2..21b39a15b121e2 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs @@ -23,11 +23,7 @@ public override string? Name get => _name; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - + ThrowHelper.ThrowIfNull(value); _name = value; } } diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs index dcc6f897814086..46f7b2a1c5a751 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs @@ -15,14 +15,18 @@ internal sealed class DefaultTypedHttpClientFactory<[DynamicallyAccessedMembers( private readonly Cache _cache; private readonly IServiceProvider _services; - public DefaultTypedHttpClientFactory(Cache cache!!, IServiceProvider services) + public DefaultTypedHttpClientFactory(Cache cache, IServiceProvider services) { + ThrowHelper.ThrowIfNull(cache); + _cache = cache; _services = services; } - public TClient CreateClient(HttpClient httpClient!!) + public TClient CreateClient(HttpClient httpClient) { + ThrowHelper.ThrowIfNull(httpClient); + return (TClient)_cache.Activator(_services, new object[] { httpClient }); } diff --git a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs index 281c29573b8d7c..e97b7f4aa2b10f 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs @@ -24,8 +24,11 @@ public static class HttpClientBuilderExtensions /// The . /// A delegate that is used to configure an . /// An that can be used to configure the client. - public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder builder!!, Action configureClient!!) + public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder builder, Action configureClient) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureClient); + builder.Services.Configure(builder.Name, options => options.HttpClientActions.Add(configureClient)); return builder; @@ -41,8 +44,11 @@ public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder bui /// The provided to will be the /// same application's root service provider instance. /// - public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder builder!!, Action configureClient!!) + public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder builder, Action configureClient) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureClient); + builder.Services.AddTransient>(services => { return new ConfigureNamedOptions(builder.Name, (options) => @@ -64,8 +70,11 @@ public static IHttpClientBuilder ConfigureHttpClient(this IHttpClientBuilder bui /// The delegate should return a new instance of the message handler each time it /// is invoked. /// - public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder!!, Func configureHandler!!) + public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureHandler); + builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.AdditionalHandlers.Add(configureHandler())); @@ -89,8 +98,11 @@ public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder b /// a reference to a scoped service provider that shares the lifetime of the handler being constructed. /// /// - public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder!!, Func configureHandler!!) + public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureHandler); + builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.AdditionalHandlers.Add(configureHandler(b.Services))); @@ -113,9 +125,11 @@ public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder b /// the lifetime of the handler being constructed. /// /// - public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder!!) + public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder) where THandler : DelegatingHandler { + ThrowHelper.ThrowIfNull(builder); + builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.AdditionalHandlers.Add(b.Services.GetRequiredService())); @@ -135,8 +149,11 @@ public static IHttpClientBuilder AddHttpMessageHandler(this IHttpClien /// The delegate should return a new instance of the message handler each time it /// is invoked. /// - public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder!!, Func configureHandler!!) + public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureHandler); + builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.PrimaryHandler = configureHandler()); @@ -162,8 +179,11 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpCl /// a reference to a scoped service provider that shares the lifetime of the handler being constructed. /// /// - public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder!!, Func configureHandler!!) + public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder, Func configureHandler) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureHandler); + builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.PrimaryHandler = configureHandler(b.Services)); @@ -187,9 +207,11 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpCl /// the lifetime of the handler being constructed. /// /// - public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder!!) + public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(this IHttpClientBuilder builder) where THandler : HttpMessageHandler { + ThrowHelper.ThrowIfNull(builder); + builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.PrimaryHandler = b.Services.GetRequiredService()); @@ -205,8 +227,11 @@ public static IHttpClientBuilder ConfigurePrimaryHttpMessageHandler(th /// The . /// A delegate that is used to configure an . /// An that can be used to configure the client. - public static IHttpClientBuilder ConfigureHttpMessageHandlerBuilder(this IHttpClientBuilder builder!!, Action configureBuilder!!) + public static IHttpClientBuilder ConfigureHttpMessageHandlerBuilder(this IHttpClientBuilder builder, Action configureBuilder) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(configureBuilder); + builder.Services.Configure(builder.Name, options => options.HttpMessageHandlerBuilderActions.Add(configureBuilder)); return builder; @@ -238,9 +263,11 @@ public static IHttpClientBuilder ConfigureHttpMessageHandlerBuilder(this IHttpCl /// /// public static IHttpClientBuilder AddTypedClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IHttpClientBuilder builder!!) + this IHttpClientBuilder builder) where TClient : class { + ThrowHelper.ThrowIfNull(builder); + return AddTypedClientCore(builder, validateSingleType: false); } @@ -298,10 +325,12 @@ private static TClient AddTransientHelper(IServiceProvider s, IHttpClie /// /// public static IHttpClientBuilder AddTypedClient( - this IHttpClientBuilder builder!!) + this IHttpClientBuilder builder) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(builder); + return AddTypedClientCore(builder, validateSingleType: false); } @@ -349,9 +378,12 @@ private static TClient AddTransientHelper(IServiceProv /// will register a typed client binding that creates using the provided factory function. /// /// - public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder!!, Func factory!!) + public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder, Func factory) where TClient : class { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(factory); + return AddTypedClientCore(builder, factory, validateSingleType: false); } @@ -392,15 +424,21 @@ internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientB /// will register a typed client binding that creates using the provided factory function. /// /// - public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder!!, Func factory!!) + public static IHttpClientBuilder AddTypedClient(this IHttpClientBuilder builder, Func factory) where TClient : class { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(factory); + return AddTypedClientCore(builder, factory, validateSingleType: false); } - internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientBuilder builder!!, Func factory!!, bool validateSingleType) + internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientBuilder builder, Func factory, bool validateSingleType) where TClient : class { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(factory); + ReserveClient(builder, typeof(TClient), builder.Name, validateSingleType); builder.Services.AddTransient(s => @@ -422,8 +460,11 @@ internal static IHttpClientBuilder AddTypedClientCore(this IHttpClientB /// The . /// The provided predicate will be evaluated for each header value when logging. If the predicate returns true then the header value will be replaced with a marker value * in logs; otherwise the header value will be logged. /// - public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder builder!!, Func shouldRedactHeaderValue!!) + public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder builder, Func shouldRedactHeaderValue) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(shouldRedactHeaderValue); + builder.Services.Configure(builder.Name, options => { options.ShouldRedactHeaderValue = shouldRedactHeaderValue; @@ -438,8 +479,11 @@ public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder bui /// The . /// The collection of HTTP headers names for which values should be redacted before logging. /// The . - public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder builder!!, IEnumerable redactedLoggedHeaderNames!!) + public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder builder, IEnumerable redactedLoggedHeaderNames) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(redactedLoggedHeaderNames); + builder.Services.Configure(builder.Name, options => { var sensitiveHeaders = new HashSet(redactedLoggedHeaderNames, StringComparer.OrdinalIgnoreCase); @@ -474,8 +518,10 @@ public static IHttpClientBuilder RedactLoggedHeaders(this IHttpClientBuilder bui /// disposed until all references are garbage-collected. /// /// - public static IHttpClientBuilder SetHandlerLifetime(this IHttpClientBuilder builder!!, TimeSpan handlerLifetime) + public static IHttpClientBuilder SetHandlerLifetime(this IHttpClientBuilder builder, TimeSpan handlerLifetime) { + ThrowHelper.ThrowIfNull(builder); + if (handlerLifetime != Timeout.InfiniteTimeSpan && handlerLifetime < HttpClientFactoryOptions.MinimumHandlerLifetime) { throw new ArgumentException(SR.HandlerLifetime_InvalidValue, nameof(handlerLifetime)); diff --git a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs index eaa1fa2f465b0e..08072f0b43987c 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs @@ -20,8 +20,10 @@ public static class HttpClientFactoryServiceCollectionExtensions /// /// The . /// The . - public static IServiceCollection AddHttpClient(this IServiceCollection services!!) + public static IServiceCollection AddHttpClient(this IServiceCollection services) { + ThrowHelper.ThrowIfNull(services); + services.AddLogging(); services.AddOptions(); @@ -73,8 +75,11 @@ public static IServiceCollection AddHttpClient(this IServiceCollection services! /// Use as the name to configure the default client. /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, string name!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + AddHttpClient(services); return new DefaultHttpClientBuilder(services, name); @@ -97,8 +102,12 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// Use as the name to configure the default client. /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, string name!!, Action configureClient!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action configureClient) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -123,8 +132,12 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// Use as the name to configure the default client. /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, string name!!, Action configureClient!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action configureClient) { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -155,9 +168,11 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services!!) + this IServiceCollection services) where TClient : class { + ThrowHelper.ThrowIfNull(services); + AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -193,10 +208,12 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services!!) + this IServiceCollection services) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -231,9 +248,12 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services!!, string name!!) + this IServiceCollection services, string name) where TClient : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -271,10 +291,13 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services!!, string name!!) + this IServiceCollection services, string name) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -306,9 +329,12 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services!!, Action configureClient!!) + this IServiceCollection services, Action configureClient) where TClient : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -342,9 +368,12 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services!!, Action configureClient!!) + this IServiceCollection services, Action configureClient) where TClient : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -382,10 +411,13 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services!!, Action configureClient!!) + this IServiceCollection services, Action configureClient) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -423,10 +455,13 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services!!, Action configureClient!!) + this IServiceCollection services, Action configureClient) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -463,9 +498,13 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services!!, string name!!, Action configureClient!!) + this IServiceCollection services, string name, Action configureClient) where TClient : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -501,9 +540,13 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services!!, string name!!, Action configureClient!!) + this IServiceCollection services, string name, Action configureClient) where TClient : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -543,10 +586,14 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services!!, string name!!, Action configureClient!!) + this IServiceCollection services, string name, Action configureClient) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -586,10 +633,14 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services!!, string name!!, Action configureClient!!) + this IServiceCollection services, string name, Action configureClient) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(configureClient); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -623,10 +674,13 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services! /// as the service type. /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, Func factory!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, Func factory) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(factory); + string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); return AddHttpClient(services, name, factory); } @@ -659,10 +713,14 @@ public static IHttpClientBuilder AddHttpClient(this IS /// /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, string name!!, Func factory!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Func factory) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(factory); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -695,10 +753,13 @@ public static IHttpClientBuilder AddHttpClient(this IS /// as the service type. /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, Func factory!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, Func factory) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(factory); + string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); return AddHttpClient(services, name, factory); } @@ -729,10 +790,14 @@ public static IHttpClientBuilder AddHttpClient(this IS /// as the service type. /// /// - public static IHttpClientBuilder AddHttpClient(this IServiceCollection services!!, string name!!, Func factory!!) + public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Func factory) where TClient : class where TImplementation : class, TClient { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(factory); + AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs index 77c798f09740cf..3719b36637c8db 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs @@ -15,8 +15,10 @@ public static class HttpClientFactoryExtensions /// /// The . /// An configured using the default configuration. - public static HttpClient CreateClient(this IHttpClientFactory factory!!) + public static HttpClient CreateClient(this IHttpClientFactory factory) { + ThrowHelper.ThrowIfNull(factory); + return factory.CreateClient(Options.DefaultName); } } diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs index 7eef2a1cc38e6e..da046ecc357438 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs @@ -78,8 +78,11 @@ public abstract class HttpMessageHandlerBuilder /// contains a entry. /// -or- /// The DelegatingHandler.InnerHandler property must be . DelegatingHandler instances provided to HttpMessageHandlerBuilder must not be reused or cached. - protected internal static HttpMessageHandler CreateHandlerPipeline(HttpMessageHandler primaryHandler!!, IEnumerable additionalHandlers!!) + protected internal static HttpMessageHandler CreateHandlerPipeline(HttpMessageHandler primaryHandler, IEnumerable additionalHandlers) { + ThrowHelper.ThrowIfNull(primaryHandler); + ThrowHelper.ThrowIfNull(additionalHandlers); + // This is similar to https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Net.Http.Formatting/HttpClientFactory.cs#L58 // but we don't want to take that package as a dependency. diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs index 823c1231669b96..068782b7a0d7f9 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs @@ -15,8 +15,10 @@ public static class HttpMessageHandlerFactoryExtensions /// /// The . /// An configured using the default configuration. - public static HttpMessageHandler CreateHandler(this IHttpMessageHandlerFactory factory!!) + public static HttpMessageHandler CreateHandler(this IHttpMessageHandlerFactory factory) { + ThrowHelper.ThrowIfNull(factory); + return factory.CreateHandler(Options.DefaultName); } } diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs index f0a1959c8f379a..b1ffecfbba2120 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs @@ -25,8 +25,10 @@ public class LoggingHttpMessageHandler : DelegatingHandler /// /// The to log to. /// is . - public LoggingHttpMessageHandler(ILogger logger!!) + public LoggingHttpMessageHandler(ILogger logger) { + ThrowHelper.ThrowIfNull(logger); + _logger = logger; } @@ -36,26 +38,35 @@ public LoggingHttpMessageHandler(ILogger logger!!) /// The to log to. /// The used to configure the instance. /// or is . - public LoggingHttpMessageHandler(ILogger logger!!, HttpClientFactoryOptions options!!) + public LoggingHttpMessageHandler(ILogger logger, HttpClientFactoryOptions options) { + ThrowHelper.ThrowIfNull(logger); + ThrowHelper.ThrowIfNull(options); + _logger = logger; _options = options; } /// /// Loggs the request to and response from the sent . - protected async override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - Func shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue; + ThrowHelper.ThrowIfNull(request); + return Core(request, cancellationToken); - // Not using a scope here because we always expect this to be at the end of the pipeline, thus there's - // not really anything to surround. - Log.RequestStart(_logger, request, shouldRedactHeaderValue); - var stopwatch = ValueStopwatch.StartNew(); - HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); - Log.RequestEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue); + async Task Core(HttpRequestMessage request, CancellationToken cancellationToken) + { + Func shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue; - return response; + // Not using a scope here because we always expect this to be at the end of the pipeline, thus there's + // not really anything to surround. + Log.RequestStart(_logger, request, shouldRedactHeaderValue); + var stopwatch = ValueStopwatch.StartNew(); + HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + Log.RequestEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue); + + return response; + } } // Used in tests. diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs index b3a6f66004578f..4907c148166099 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs @@ -14,14 +14,19 @@ internal sealed class LoggingHttpMessageHandlerBuilderFilter : IHttpMessageHandl private readonly ILoggerFactory _loggerFactory; private readonly IOptionsMonitor _optionsMonitor; - public LoggingHttpMessageHandlerBuilderFilter(ILoggerFactory loggerFactory!!, IOptionsMonitor optionsMonitor!!) + public LoggingHttpMessageHandlerBuilderFilter(ILoggerFactory loggerFactory, IOptionsMonitor optionsMonitor) { + ThrowHelper.ThrowIfNull(loggerFactory); + ThrowHelper.ThrowIfNull(optionsMonitor); + _loggerFactory = loggerFactory; _optionsMonitor = optionsMonitor; } - public Action Configure(Action next!!) + public Action Configure(Action next) { + ThrowHelper.ThrowIfNull(next); + return (builder) => { // Run other configuration first, we want to decorate. diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs index 3ac0b12889242a..2ef5fbe589514a 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs @@ -25,8 +25,10 @@ public class LoggingScopeHttpMessageHandler : DelegatingHandler /// /// The to log to. /// is . - public LoggingScopeHttpMessageHandler(ILogger logger!!) + public LoggingScopeHttpMessageHandler(ILogger logger) { + ThrowHelper.ThrowIfNull(logger); + _logger = logger; } @@ -36,27 +38,36 @@ public LoggingScopeHttpMessageHandler(ILogger logger!!) /// The to log to. /// The used to configure the instance. /// or is . - public LoggingScopeHttpMessageHandler(ILogger logger!!, HttpClientFactoryOptions options!!) + public LoggingScopeHttpMessageHandler(ILogger logger, HttpClientFactoryOptions options) { + ThrowHelper.ThrowIfNull(logger); + ThrowHelper.ThrowIfNull(options); + _logger = logger; _options = options; } /// /// Loggs the request to and response from the sent . - protected async override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - var stopwatch = ValueStopwatch.StartNew(); + ThrowHelper.ThrowIfNull(request); + return Core(request, cancellationToken); - Func shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue; - - using (Log.BeginRequestPipelineScope(_logger, request)) + async Task Core(HttpRequestMessage request, CancellationToken cancellationToken) { - Log.RequestPipelineStart(_logger, request, shouldRedactHeaderValue); - HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); - Log.RequestPipelineEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue); + var stopwatch = ValueStopwatch.StartNew(); + + Func shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue; - return response; + using (Log.BeginRequestPipelineScope(_logger, request)) + { + Log.RequestPipelineStart(_logger, request, shouldRedactHeaderValue); + HttpResponseMessage response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + Log.RequestPipelineEnd(_logger, response, stopwatch.GetElapsedTime(), shouldRedactHeaderValue); + + return response; + } } } diff --git a/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj b/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj index 5e40a002ca65c3..0a18eb7e1726b4 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj +++ b/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj @@ -18,6 +18,8 @@ System.Net.Http.IHttpClientFactory Link="Common\src\Extensions\NonCapturingTimer\NonCapturingTimer.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs index 4d2b3e66c96a93..d9bdec58babd50 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs @@ -23,8 +23,10 @@ internal sealed class LogValuesFormatter // - Be annotated as [SkipLocalsInit] to avoid zero'ing the stackalloc'd char span // - Format _valueNames.Count directly into a span - public LogValuesFormatter(string format!!) + public LogValuesFormatter(string format) { + ThrowHelper.ThrowIfNull(format); + OriginalFormat = format; var vsb = new ValueStringBuilder(stackalloc char[256]); diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs index f7cb48e4c498b5..80e9bb35b778f5 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs @@ -383,8 +383,10 @@ public static void Log(this ILogger logger, LogLevel logLevel, Exception? except /// The exception to log. /// Format string of the log message. /// An object array that contains zero or more objects to format. - public static void Log(this ILogger logger!!, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args) + public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args) { + ThrowHelper.ThrowIfNull(logger); + logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } @@ -403,10 +405,12 @@ public static void Log(this ILogger logger!!, LogLevel logLevel, EventId eventId /// } /// public static IDisposable? BeginScope( - this ILogger logger!!, + this ILogger logger, string messageFormat, params object?[] args) { + ThrowHelper.ThrowIfNull(logger); + return logger.BeginScope(new FormattedLogValues(messageFormat, args)); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs index 6333a7e7b676f6..c31c3b31214705 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs @@ -17,8 +17,10 @@ public static class LoggerFactoryExtensions /// The factory. /// The type. /// The that was created. - public static ILogger CreateLogger(this ILoggerFactory factory!!) + public static ILogger CreateLogger(this ILoggerFactory factory) { + ThrowHelper.ThrowIfNull(factory); + return new Logger(factory); } /// @@ -27,8 +29,11 @@ public static ILogger CreateLogger(this ILoggerFactory factory!!) /// The factory. /// The type. /// The that was created. - public static ILogger CreateLogger(this ILoggerFactory factory!!, Type type!!) + public static ILogger CreateLogger(this ILoggerFactory factory, Type type) { + ThrowHelper.ThrowIfNull(factory); + ThrowHelper.ThrowIfNull(type); + return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, includeGenericParameters: false, nestedTypeDelimiter: '.')); } } diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs index 3b9a3442d0bb1b..b6bf6f882f6990 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs @@ -19,8 +19,10 @@ public class Logger : ILogger /// Creates a new . /// /// The factory. - public Logger(ILoggerFactory factory!!) + public Logger(ILoggerFactory factory) { + ThrowHelper.ThrowIfNull(factory); + _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), includeGenericParameters: false, nestedTypeDelimiter: '.')); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj index eb95f66e4f5a36..66954f5e1c3c2b 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj @@ -30,6 +30,8 @@ Microsoft.Extensions.Logging.Abstractions.NullLogger Link="Common\src\Extensions\Logging\NullScope.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs index 7ef23868859706..4cd41c18ff6053 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerProviderConfigurationFactory.cs @@ -16,8 +16,10 @@ public LoggerProviderConfigurationFactory(IEnumerable conf _configurations = configurations; } - public IConfiguration GetConfiguration(Type providerType!!) + public IConfiguration GetConfiguration(Type providerType) { + ThrowHelper.ThrowIfNull(providerType); + string fullName = providerType.FullName!; string? alias = ProviderAliasUtilities.GetAlias(providerType); var configurationBuilder = new ConfigurationBuilder(); diff --git a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj index ad081b827d5cc9..e0f86108a3d98a 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) @@ -13,6 +13,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs index 8d87d6b0fa2def..de3eb09e71c399 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs @@ -10,8 +10,10 @@ namespace Microsoft.Extensions.Logging.Console internal sealed class AnsiParser { private readonly Action _onParseWrite; - public AnsiParser(Action onParseWrite!!) + public AnsiParser(Action onParseWrite) { + ThrowHelper.ThrowIfNull(onParseWrite); + _onParseWrite = onParseWrite; } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs index 0fbaaf80a8e1ec..e7a8c7eeb37a2e 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs @@ -12,8 +12,10 @@ namespace Microsoft.Extensions.Logging.Console /// public abstract class ConsoleFormatter { - protected ConsoleFormatter(string name!!) + protected ConsoleFormatter(string name) { + ThrowHelper.ThrowIfNull(name); + Name = name; } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs index 608e7bbcbfad0d..1d4e9c4400117f 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs @@ -16,12 +16,14 @@ internal sealed class ConsoleLogger : ILogger private readonly ConsoleLoggerProcessor _queueProcessor; internal ConsoleLogger( - string name!!, + string name, ConsoleLoggerProcessor loggerProcessor, ConsoleFormatter formatter, IExternalScopeProvider? scopeProvider, ConsoleLoggerOptions options) { + ThrowHelper.ThrowIfNull(name); + _name = name; _queueProcessor = loggerProcessor; Formatter = formatter; @@ -42,10 +44,9 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except { return; } - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } + + ThrowHelper.ThrowIfNull(formatter); + t_stringWriter ??= new StringWriter(); LogEntry logEntry = new LogEntry(logLevel, _name, eventId, state, exception, formatter); Formatter.Write(in logEntry, ScopeProvider, t_stringWriter); diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs index ef1e80a113627a..9df43d02c54c38 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs @@ -44,8 +44,10 @@ public static ILoggingBuilder AddConsole(this ILoggingBuilder builder) /// /// The to use. /// A delegate to configure the . - public static ILoggingBuilder AddConsole(this ILoggingBuilder builder, Action configure!!) + public static ILoggingBuilder AddConsole(this ILoggingBuilder builder, Action configure) { + ThrowHelper.ThrowIfNull(configure); + builder.AddConsole(); builder.Services.Configure(configure); @@ -103,9 +105,11 @@ public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder, Ac public static ILoggingBuilder AddSystemdConsole(this ILoggingBuilder builder) => builder.AddFormatterWithName(ConsoleFormatterNames.Systemd); - internal static ILoggingBuilder AddConsoleWithFormatter(this ILoggingBuilder builder, string name, Action configure!!) + internal static ILoggingBuilder AddConsoleWithFormatter(this ILoggingBuilder builder, string name, Action configure) where TOptions : ConsoleFormatterOptions { + ThrowHelper.ThrowIfNull(configure); + builder.AddFormatterWithName(name); builder.Services.Configure(configure); @@ -139,10 +143,12 @@ private static ILoggingBuilder AddFormatterWithName(this ILoggingBuilder builder /// The to use. /// A delegate to configure options 'TOptions' for custom formatter 'TFormatter'. [RequiresUnreferencedCode(TrimmingRequiresUnreferencedCodeMessage)] - public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this ILoggingBuilder builder, Action configure!!) + public static ILoggingBuilder AddConsoleFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TFormatter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this ILoggingBuilder builder, Action configure) where TOptions : ConsoleFormatterOptions where TFormatter : ConsoleFormatter { + ThrowHelper.ThrowIfNull(configure); + builder.AddConsoleFormatter(); builder.Services.Configure(configure); return builder; diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj b/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj index 4fc4123708397d..471f83cc8a92ea 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj @@ -1,4 +1,4 @@ - + $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) @@ -21,6 +21,8 @@ Link="Common\src\Extensions\Logging\NullScope.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs b/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs index 8ff824ea3f3f36..f84e641ace3ddd 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.cs @@ -44,10 +44,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } + ThrowHelper.ThrowIfNull(formatter); string message = formatter(state, exception); diff --git a/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj b/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj index d522b2eb650f6e..5733b046302c54 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj @@ -15,6 +15,8 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs index 5baa17b92e31fc..e4b89bdb925693 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs @@ -27,8 +27,11 @@ internal sealed class EventLogLogger : ILogger /// The name of the logger. /// The . /// The . - public EventLogLogger(string name!!, EventLogSettings settings!!, IExternalScopeProvider? externalScopeProvider) + public EventLogLogger(string name, EventLogSettings settings, IExternalScopeProvider? externalScopeProvider) { + ThrowHelper.ThrowIfNull(name); + ThrowHelper.ThrowIfNull(settings); + _name = name; _settings = settings; @@ -73,10 +76,7 @@ public void Log( return; } - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } + ThrowHelper.ThrowIfNull(formatter); string message = formatter(state, exception); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs index 17c2c8b0466269..8ac843c859af08 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs @@ -18,8 +18,10 @@ public static class EventLoggerFactoryExtensions /// /// The extension method argument. /// The so that additional calls can be chained. - public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder!!) + public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder) { + ThrowHelper.ThrowIfNull(builder); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); return builder; @@ -31,8 +33,11 @@ public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder!!) /// The extension method argument. /// The . /// The so that additional calls can be chained. - public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder!!, EventLogSettings settings!!) + public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, EventLogSettings settings) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(settings); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(new EventLogLoggerProvider(settings))); return builder; @@ -44,8 +49,10 @@ public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder!!, EventL /// The extension method argument. /// A delegate to configure the . /// The so that additional calls can be chained. - public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, Action configure!!) + public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, Action configure) { + ThrowHelper.ThrowIfNull(configure); + builder.AddEventLog(); builder.Services.Configure(configure); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj index a9fbd16bc25df9..7d28da7c90437e 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj @@ -15,6 +15,8 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs index de15d2e5b0ea8f..7f247bd6caec92 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs @@ -19,8 +19,10 @@ public static class EventSourceLoggerFactoryExtensions /// /// The extension method argument. /// The so that additional calls can be chained. - public static ILoggingBuilder AddEventSourceLogger(this ILoggingBuilder builder!!) + public static ILoggingBuilder AddEventSourceLogger(this ILoggingBuilder builder) { + ThrowHelper.ThrowIfNull(builder); + builder.Services.TryAddSingleton(LoggingEventSource.Instance); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, EventLogFiltersConfigureOptions>()); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs index ddddd58bd0231e..9c62c8f175a816 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs @@ -20,8 +20,10 @@ public class EventSourceLoggerProvider : ILoggerProvider private EventSourceLogger? _loggers; // Linked list of loggers that I have created private readonly LoggingEventSource _eventSource; - public EventSourceLoggerProvider(LoggingEventSource eventSource!!) + public EventSourceLoggerProvider(LoggingEventSource eventSource) { + ThrowHelper.ThrowIfNull(eventSource); + _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); } diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj index 24ebe234362706..5333a89539ea87 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj @@ -16,6 +16,8 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj index 3f310e94ed40e3..70b7e15234b3ce 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj @@ -14,6 +14,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs index d4288e3fd7bb80..e8d2bba55a0b16 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs @@ -20,9 +20,12 @@ public static class TraceSourceFactoryExtensions /// The name of the to use. /// The so that additional calls can be chained. public static ILoggingBuilder AddTraceSource( - this ILoggingBuilder builder!!, - string switchName!!) + this ILoggingBuilder builder, + string switchName) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(switchName); + return builder.AddTraceSource(new SourceSwitch(switchName)); } @@ -34,10 +37,14 @@ public static ILoggingBuilder AddTraceSource( /// The to use. /// The so that additional calls can be chained. public static ILoggingBuilder AddTraceSource( - this ILoggingBuilder builder!!, - string switchName!!, - TraceListener listener!!) + this ILoggingBuilder builder, + string switchName, + TraceListener listener) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(switchName); + ThrowHelper.ThrowIfNull(listener); + return builder.AddTraceSource(new SourceSwitch(switchName), listener); } @@ -48,9 +55,12 @@ public static ILoggingBuilder AddTraceSource( /// The to use. /// The so that additional calls can be chained. public static ILoggingBuilder AddTraceSource( - this ILoggingBuilder builder!!, - SourceSwitch sourceSwitch!!) + this ILoggingBuilder builder, + SourceSwitch sourceSwitch) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(sourceSwitch); + builder.Services.AddSingleton(_ => new TraceSourceLoggerProvider(sourceSwitch)); return builder; @@ -64,10 +74,14 @@ public static ILoggingBuilder AddTraceSource( /// The to use. /// The so that additional calls can be chained. public static ILoggingBuilder AddTraceSource( - this ILoggingBuilder builder!!, - SourceSwitch sourceSwitch!!, - TraceListener listener!!) + this ILoggingBuilder builder, + SourceSwitch sourceSwitch, + TraceListener listener) { + ThrowHelper.ThrowIfNull(builder); + ThrowHelper.ThrowIfNull(sourceSwitch); + ThrowHelper.ThrowIfNull(listener); + builder.Services.AddSingleton(_ => new TraceSourceLoggerProvider(sourceSwitch, listener)); return builder; diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs index 3eabe588fce3b1..c39c6b5f2f4f81 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs @@ -35,8 +35,10 @@ public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch) /// /// The to use. /// The to use. - public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch!!, TraceListener? rootTraceListener) + public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch, TraceListener? rootTraceListener) { + ThrowHelper.ThrowIfNull(rootSourceSwitch); + _rootSourceSwitch = rootSourceSwitch; _rootTraceListener = rootTraceListener; } diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs index f699fcc8f3056b..219fdf0031bc05 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs @@ -151,10 +151,7 @@ public void AddProvider(ILoggerProvider provider) throw new ObjectDisposedException(nameof(LoggerFactory)); } - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ThrowHelper.ThrowIfNull(provider); lock (_sync) { diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs index b04b31b87d4125..e9f15e2804de3a 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs @@ -29,8 +29,10 @@ public static IServiceCollection AddLogging(this IServiceCollection services) /// The to add services to. /// The configuration delegate. /// The so that additional calls can be chained. - public static IServiceCollection AddLogging(this IServiceCollection services!!, Action configure) + public static IServiceCollection AddLogging(this IServiceCollection services, Action configure) { + ThrowHelper.ThrowIfNull(services); + services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); diff --git a/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj b/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj index 1ecc628f4d47a9..dbf1b2a33f186b 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj +++ b/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj @@ -17,6 +17,8 @@ Link="Common\src\Extensions\Logging\NullExternalScopeProvider.cs" /> + diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs index 2a2e1e72c41223..d93940902d0af2 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs @@ -29,8 +29,10 @@ public ConfigurationChangeTokenSource(IConfiguration config) : this(Options.Defa /// /// The name of the options instance being watched. /// The configuration instance. - public ConfigurationChangeTokenSource(string? name, IConfiguration config!!) + public ConfigurationChangeTokenSource(string? name, IConfiguration config) { + ThrowHelper.ThrowIfNull(config); + _config = config; Name = name ?? Options.DefaultName; } diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs index c0bd89c168ea24..b4190cf4d90b27 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs @@ -23,9 +23,10 @@ public class ConfigureFromConfigurationOptions<[DynamicallyAccessedMembers(Dynam /// The instance. //Even though TOptions is annotated, we need to annotate as RUC as we can't guarantee properties on referenced types are preserved. [RequiresUnreferencedCode(OptionsBuilderConfigurationExtensions.TrimmingRequiredUnreferencedCodeMessage)] - public ConfigureFromConfigurationOptions(IConfiguration config!!) + public ConfigureFromConfigurationOptions(IConfiguration config) : base(options => BindFromOptions(options, config)) { + ThrowHelper.ThrowIfNull(config); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj index 1e84f04442a5bd..7bc710cb5fe9bb 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/Microsoft.Extensions.Options.ConfigurationExtensions.csproj @@ -23,6 +23,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs index 65a0e12722d883..b91aab542cec78 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs @@ -32,9 +32,10 @@ public NamedConfigureFromConfigurationOptions(string? name, IConfiguration confi /// The instance. /// Used to configure the . [RequiresUnreferencedCode(OptionsBuilderConfigurationExtensions.TrimmingRequiredUnreferencedCodeMessage)] - public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config!!, Action? configureBinder) + public NamedConfigureFromConfigurationOptions(string? name, IConfiguration config, Action? configureBinder) : base(name, options => BindFromOptions(options, config, configureBinder)) { + ThrowHelper.ThrowIfNull(config); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs index 8e8814f13fedd5..6f73a1959ef7a4 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs @@ -35,8 +35,10 @@ public static class OptionsBuilderConfigurationExtensions /// Used to configure the . /// The so that additional calls can be chained. [RequiresUnreferencedCode(TrimmingRequiredUnreferencedCodeMessage)] - public static OptionsBuilder Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder optionsBuilder!!, IConfiguration config, Action? configureBinder) where TOptions : class + public static OptionsBuilder Bind<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this OptionsBuilder optionsBuilder, IConfiguration config, Action? configureBinder) where TOptions : class { + ThrowHelper.ThrowIfNull(optionsBuilder); + optionsBuilder.Services.Configure(optionsBuilder.Name, config, configureBinder); return optionsBuilder; } @@ -56,11 +58,14 @@ public static class OptionsBuilderConfigurationExtensions /// [RequiresUnreferencedCode(TrimmingRequiredUnreferencedCodeMessage)] public static OptionsBuilder BindConfiguration<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>( - this OptionsBuilder optionsBuilder!!, - string configSectionPath!!, + this OptionsBuilder optionsBuilder, + string configSectionPath, Action? configureBinder = null) where TOptions : class { + ThrowHelper.ThrowIfNull(optionsBuilder); + ThrowHelper.ThrowIfNull(configSectionPath); + optionsBuilder.Configure((opts, config) => BindFromOptions(opts, config, configSectionPath, configureBinder)); optionsBuilder.Services.AddSingleton, ConfigurationChangeTokenSource>(); return optionsBuilder; diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs index a6f2196e6a6472..2b1e2015b0dfc2 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs @@ -59,9 +59,12 @@ public static class OptionsConfigurationServiceCollectionExtensions /// Used to configure the . /// The so that additional calls can be chained. [RequiresUnreferencedCode(OptionsBuilderConfigurationExtensions.TrimmingRequiredUnreferencedCodeMessage)] - public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services!!, string? name, IConfiguration config!!, Action? configureBinder) + public static IServiceCollection Configure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TOptions>(this IServiceCollection services, string? name, IConfiguration config, Action? configureBinder) where TOptions : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(config); + services.AddOptions(); services.AddSingleton>(new ConfigurationChangeTokenSource(name, config)); return services.AddSingleton>(new NamedConfigureFromConfigurationOptions(name, config, configureBinder)); diff --git a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs index c3e025873b7f11..446f7d22a43725 100644 --- a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.cs @@ -49,10 +49,7 @@ public ValidateOptionsResult Validate(string? name, TOptions options) } // Ensure options are provided to validate against - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ThrowHelper.ThrowIfNull(options); var validationResults = new List(); if (Validator.TryValidateObject(options, new ValidationContext(options), validationResults, validateAllProperties: true)) diff --git a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj index 1ba2440004af9a..2aea49a0e64ba9 100644 --- a/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj +++ b/src/libraries/Microsoft.Extensions.Options.DataAnnotations/src/Microsoft.Extensions.Options.DataAnnotations.csproj @@ -11,6 +11,7 @@ + diff --git a/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs index a3f9409c7686bc..487416e329c30c 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs @@ -37,8 +37,10 @@ public ConfigureNamedOptions(string? name, Action? action) /// /// The name of the options instance being configured. /// The options instance to configure. - public virtual void Configure(string? name, TOptions options!!) + public virtual void Configure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -95,8 +97,10 @@ public ConfigureNamedOptions(string? name, TDep dependency, Action /// The name of the options instance being configured. /// The options instance to configure. - public virtual void Configure(string? name, TOptions options!!) + public virtual void Configure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -162,8 +166,10 @@ public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, /// /// The name of the options instance being configured. /// The options instance to configure. - public virtual void Configure(string? name, TOptions options!!) + public virtual void Configure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -238,8 +244,10 @@ public ConfigureNamedOptions(string? name, TDep1 dependency, TDep2 dependency2, /// /// The name of the options instance being configured. /// The options instance to configure. - public virtual void Configure(string? name, TOptions options!!) + public virtual void Configure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -323,8 +331,10 @@ public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// /// The name of the options instance being configured. /// The options instance to configure. - public virtual void Configure(string? name, TOptions options!!) + public virtual void Configure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -417,8 +427,10 @@ public ConfigureNamedOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// /// The name of the options instance being configured. /// The options instance to configure. - public virtual void Configure(string? name, TOptions options!!) + public virtual void Configure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { diff --git a/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs index 556f45bc1ca324..af155cf9aa89c7 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs @@ -29,8 +29,10 @@ public ConfigureOptions(Action? action) /// Invokes the registered configure . /// /// The options instance to configure. - public virtual void Configure(TOptions options!!) + public virtual void Configure(TOptions options) { + ThrowHelper.ThrowIfNull(options); + Action?.Invoke(options); } } diff --git a/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj b/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj index f593699339b916..462166ac1dbb5d 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj +++ b/src/libraries/Microsoft.Extensions.Options/src/Microsoft.Extensions.Options.csproj @@ -20,6 +20,8 @@ + diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs index 5819ee059a04d2..33d4c9fb0f19b2 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs @@ -29,8 +29,10 @@ public class OptionsBuilder where TOptions : class /// /// The for the options being configured. /// The default name of the instance, if null is used. - public OptionsBuilder(IServiceCollection services!!, string? name) + public OptionsBuilder(IServiceCollection services, string? name) { + ThrowHelper.ThrowIfNull(services); + Services = services; Name = name ?? Options.DefaultName; } @@ -41,8 +43,10 @@ public OptionsBuilder(IServiceCollection services!!, string? name) /// /// The action used to configure the options. /// The current . - public virtual OptionsBuilder Configure(Action configureOptions!!) + public virtual OptionsBuilder Configure(Action configureOptions) { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddSingleton>(new ConfigureNamedOptions(Name, configureOptions)); return this; } @@ -54,9 +58,11 @@ public virtual OptionsBuilder Configure(Action configureOpti /// A dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder Configure(Action configureOptions!!) + public virtual OptionsBuilder Configure(Action configureOptions) where TDep : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>(sp => new ConfigureNamedOptions(Name, sp.GetRequiredService(), configureOptions)); return this; @@ -70,10 +76,12 @@ public virtual OptionsBuilder Configure(Action c /// The second dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder Configure(Action configureOptions!!) + public virtual OptionsBuilder Configure(Action configureOptions) where TDep1 : class where TDep2 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>(sp => new ConfigureNamedOptions(Name, sp.GetRequiredService(), sp.GetRequiredService(), configureOptions)); return this; @@ -88,11 +96,13 @@ public virtual OptionsBuilder Configure(ActionThe third dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder Configure(Action configureOptions!!) + public virtual OptionsBuilder Configure(Action configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>( sp => new ConfigureNamedOptions( Name, @@ -113,12 +123,14 @@ public virtual OptionsBuilder Configure(ActionThe fourth dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder Configure(Action configureOptions!!) + public virtual OptionsBuilder Configure(Action configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>( sp => new ConfigureNamedOptions( Name, @@ -141,13 +153,15 @@ public virtual OptionsBuilder Configure(Ac /// The fifth dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder Configure(Action configureOptions!!) + public virtual OptionsBuilder Configure(Action configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>( sp => new ConfigureNamedOptions( Name, @@ -165,8 +179,10 @@ public virtual OptionsBuilder Configure. /// /// The action used to configure the options. - public virtual OptionsBuilder PostConfigure(Action configureOptions!!) + public virtual OptionsBuilder PostConfigure(Action configureOptions) { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddSingleton>(new PostConfigureOptions(Name, configureOptions)); return this; } @@ -178,9 +194,11 @@ public virtual OptionsBuilder PostConfigure(Action configure /// The dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder PostConfigure(Action configureOptions!!) + public virtual OptionsBuilder PostConfigure(Action configureOptions) where TDep : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>(sp => new PostConfigureOptions(Name, sp.GetRequiredService(), configureOptions)); return this; @@ -194,10 +212,12 @@ public virtual OptionsBuilder PostConfigure(ActionThe second dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder PostConfigure(Action configureOptions!!) + public virtual OptionsBuilder PostConfigure(Action configureOptions) where TDep1 : class where TDep2 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>(sp => new PostConfigureOptions(Name, sp.GetRequiredService(), sp.GetRequiredService(), configureOptions)); return this; @@ -212,11 +232,13 @@ public virtual OptionsBuilder PostConfigure(ActionThe third dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder PostConfigure(Action configureOptions!!) + public virtual OptionsBuilder PostConfigure(Action configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>( sp => new PostConfigureOptions( Name, @@ -237,12 +259,14 @@ public virtual OptionsBuilder PostConfigure(Actio /// The fourth dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder PostConfigure(Action configureOptions!!) + public virtual OptionsBuilder PostConfigure(Action configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>( sp => new PostConfigureOptions( Name, @@ -265,13 +289,15 @@ public virtual OptionsBuilder PostConfigureThe fifth dependency used by the action. /// The action used to configure the options. /// The current . - public virtual OptionsBuilder PostConfigure(Action configureOptions!!) + public virtual OptionsBuilder PostConfigure(Action configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { + ThrowHelper.ThrowIfNull(configureOptions); + Services.AddTransient>( sp => new PostConfigureOptions( Name, @@ -298,8 +324,10 @@ public virtual OptionsBuilder Validate(Func validation /// The validation function. /// The failure message to use when validation fails. /// The current . - public virtual OptionsBuilder Validate(Func validation!!, string failureMessage) + public virtual OptionsBuilder Validate(Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Services.AddSingleton>(new ValidateOptions(Name, validation, failureMessage)); return this; } @@ -320,8 +348,10 @@ public virtual OptionsBuilder Validate(FuncThe validation function. /// The failure message to use when validation fails. /// The current . - public virtual OptionsBuilder Validate(Func validation!!, string failureMessage) where TDep : notnull + public virtual OptionsBuilder Validate(Func validation, string failureMessage) where TDep : notnull { + ThrowHelper.ThrowIfNull(validation); + Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), validation, failureMessage)); return this; @@ -347,10 +377,12 @@ public virtual OptionsBuilder Validate(FuncThe validation function. /// The failure message to use when validation fails. /// The current . - public virtual OptionsBuilder Validate(Func validation!!, string failureMessage) + public virtual OptionsBuilder Validate(Func validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull { + ThrowHelper.ThrowIfNull(validation); + Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), @@ -383,11 +415,13 @@ public virtual OptionsBuilder Validate(FuncThe validation function. /// The failure message to use when validation fails. /// The current . - public virtual OptionsBuilder Validate(Func validation!!, string failureMessage) + public virtual OptionsBuilder Validate(Func validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull { + ThrowHelper.ThrowIfNull(validation); + Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), @@ -424,12 +458,14 @@ public virtual OptionsBuilder Validate(Fun /// The validation function. /// The failure message to use when validation fails. /// The current . - public virtual OptionsBuilder Validate(Func validation!!, string failureMessage) + public virtual OptionsBuilder Validate(Func validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull { + ThrowHelper.ThrowIfNull(validation); + Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), @@ -470,13 +506,15 @@ public virtual OptionsBuilder ValidateThe validation function. /// The failure message to use when validation fails. /// The current . - public virtual OptionsBuilder Validate(Func validation!!, string failureMessage) + public virtual OptionsBuilder Validate(Func validation, string failureMessage) where TDep1 : notnull where TDep2 : notnull where TDep3 : notnull where TDep4 : notnull where TDep5 : notnull { + ThrowHelper.ThrowIfNull(validation); + Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs index 902f314bf8124e..9be845ca4e8b71 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs @@ -28,8 +28,10 @@ public class OptionsCache<[DynamicallyAccessedMembers(Options.DynamicallyAccesse /// The name of the options instance. /// The func used to create the new instance. /// The options instance. - public virtual TOptions GetOrAdd(string? name, Func createOptions!!) + public virtual TOptions GetOrAdd(string? name, Func createOptions) { + ThrowHelper.ThrowIfNull(createOptions); + name ??= Options.DefaultName; Lazy value; @@ -91,8 +93,10 @@ internal bool TryGetValue(string? name, [MaybeNullWhen(false)] out TOptions opti /// The name of the options instance. /// The options instance. /// Whether anything was added. - public virtual bool TryAdd(string? name, TOptions options!!) + public virtual bool TryAdd(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + return _cache.TryAdd(name ?? Options.DefaultName, new Lazy( #if !(NET || NETSTANDARD2_1) () => diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs index 73e3c4396f915c..1d30bd1155b9a4 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs @@ -19,8 +19,10 @@ public static class OptionsServiceCollectionExtensions /// /// The to add the services to. /// The so that additional calls can be chained. - public static IServiceCollection AddOptions(this IServiceCollection services!!) + public static IServiceCollection AddOptions(this IServiceCollection services) { + ThrowHelper.ThrowIfNull(services); + services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(UnnamedOptionsManager<>))); services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>))); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>))); @@ -49,9 +51,12 @@ public static IServiceCollection Configure(this IServiceCollection ser /// The name of the options instance. /// The action used to configure the options. /// The so that additional calls can be chained. - public static IServiceCollection Configure(this IServiceCollection services!!, string? name, Action configureOptions!!) + public static IServiceCollection Configure(this IServiceCollection services, string? name, Action configureOptions) where TOptions : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(configureOptions); + services.AddOptions(); services.AddSingleton>(new ConfigureNamedOptions(name, configureOptions)); return services; @@ -87,9 +92,12 @@ public static IServiceCollection PostConfigure(this IServiceCollection /// The name of the options instance. /// The action used to configure the options. /// The so that additional calls can be chained. - public static IServiceCollection PostConfigure(this IServiceCollection services!!, string? name, Action configureOptions!!) + public static IServiceCollection PostConfigure(this IServiceCollection services, string? name, Action configureOptions) where TOptions : class { + ThrowHelper.ThrowIfNull(services); + ThrowHelper.ThrowIfNull(configureOptions); + services.AddOptions(); services.AddSingleton>(new PostConfigureOptions(name, configureOptions)); return services; @@ -225,9 +233,11 @@ public static OptionsBuilder AddOptions(this IServiceCollect /// The to add the services to. /// The name of the options instance. /// The so that configure calls can be chained in it. - public static OptionsBuilder AddOptions(this IServiceCollection services!!, string? name) + public static OptionsBuilder AddOptions(this IServiceCollection services, string? name) where TOptions : class { + ThrowHelper.ThrowIfNull(services); + services.AddOptions(); return new OptionsBuilder(services, name); } diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs index f5b4bcf7959427..c2475535aa898f 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs @@ -17,8 +17,11 @@ public class OptionsValidationException : Exception /// The name of the options instance that failed. /// The options type that failed. /// The validation failure messages. - public OptionsValidationException(string optionsName!!, Type optionsType!!, IEnumerable? failureMessages) + public OptionsValidationException(string optionsName, Type optionsType, IEnumerable? failureMessages) { + ThrowHelper.ThrowIfNull(optionsName); + ThrowHelper.ThrowIfNull(optionsType); + Failures = failureMessages ?? new List(); OptionsType = optionsType; OptionsName = optionsName; diff --git a/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs index 138220ac9e4049..7106a974f1abf7 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs @@ -37,8 +37,10 @@ public PostConfigureOptions(string? name, Action? action) /// /// The name of the action to invoke. /// The options to use in initialization. - public virtual void PostConfigure(string? name, TOptions options!!) + public virtual void PostConfigure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to initialize all named options. if (Name == null || name == Name) { @@ -89,8 +91,10 @@ public PostConfigureOptions(string? name, TDep dependency, Action /// The name of the options instance being configured. /// The options instance to configured. - public virtual void PostConfigure(string? name, TOptions options!!) + public virtual void PostConfigure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -156,8 +160,10 @@ public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, A /// /// The name of the options instance being configured. /// The options instance to configured. - public virtual void PostConfigure(string? name, TOptions options!!) + public virtual void PostConfigure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -232,8 +238,10 @@ public PostConfigureOptions(string? name, TDep1 dependency, TDep2 dependency2, T /// /// The name of the options instance being configured. /// The options instance to configured. - public virtual void PostConfigure(string? name, TOptions options!!) + public virtual void PostConfigure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -317,8 +325,10 @@ public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// /// The name of the options instance being configured. /// The options instance to configured. - public virtual void PostConfigure(string? name, TOptions options!!) + public virtual void PostConfigure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -411,8 +421,10 @@ public PostConfigureOptions(string? name, TDep1 dependency1, TDep2 dependency2, /// /// The name of the options instance being configured. /// The options instance to configured. - public virtual void PostConfigure(string? name, TOptions options!!) + public virtual void PostConfigure(string? name, TOptions options) { + ThrowHelper.ThrowIfNull(options); + // Null name is used to configure all named options. if (Name == null || name == Name) { diff --git a/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs index de083ed427d5d5..ad8877f23dedd7 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ValidateOptions.cs @@ -17,8 +17,10 @@ public class ValidateOptions : IValidateOptions where TOptio /// Options name. /// Validation function. /// Validation failure message. - public ValidateOptions(string? name, Func validation!!, string failureMessage) + public ValidateOptions(string? name, Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Name = name; Validation = validation; FailureMessage = failureMessage; @@ -76,8 +78,10 @@ public class ValidateOptions : IValidateOptions where /// The dependency. /// Validation function. /// Validation failure message. - public ValidateOptions(string? name, TDep dependency, Func validation!!, string failureMessage) + public ValidateOptions(string? name, TDep dependency, Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Name = name; Validation = validation; FailureMessage = failureMessage; @@ -143,8 +147,10 @@ public class ValidateOptions : IValidateOptionsThe second dependency. /// Validation function. /// Validation failure message. - public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, Func validation!!, string failureMessage) + public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Name = name; Validation = validation; FailureMessage = failureMessage; @@ -218,8 +224,10 @@ public class ValidateOptions : IValidateOptionsThe third dependency. /// Validation function. /// Validation failure message. - public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, Func validation!!, string failureMessage) + public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Name = name; Validation = validation; FailureMessage = failureMessage; @@ -301,8 +309,10 @@ public class ValidateOptions : IValidateOp /// The fourth dependency. /// Validation function. /// Validation failure message. - public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Func validation!!, string failureMessage) + public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Name = name; Validation = validation; FailureMessage = failureMessage; @@ -392,8 +402,10 @@ public class ValidateOptions : IVal /// The fifth dependency. /// Validation function. /// Validation failure message. - public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Func validation!!, string failureMessage) + public ValidateOptions(string? name, TDep1 dependency1, TDep2 dependency2, TDep3 dependency3, TDep4 dependency4, TDep5 dependency5, Func validation, string failureMessage) { + ThrowHelper.ThrowIfNull(validation); + Name = name; Validation = validation; FailureMessage = failureMessage; diff --git a/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs b/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs index 45a35ff3c0fffc..75dbb217e26f67 100644 --- a/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs +++ b/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs @@ -18,8 +18,17 @@ public static class ChangeToken /// Produces the change token. /// Action called when the token changes. /// - public static IDisposable OnChange(Func changeTokenProducer!!, Action changeTokenConsumer!!) + public static IDisposable OnChange(Func changeTokenProducer, Action changeTokenConsumer) { + if (changeTokenProducer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer); + } + if (changeTokenConsumer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer); + } + return new ChangeTokenRegistration(changeTokenProducer, callback => callback(), changeTokenConsumer); } @@ -30,8 +39,17 @@ public static IDisposable OnChange(Func changeTokenProducer!!, Ac /// Action called when the token changes. /// state for the consumer. /// - public static IDisposable OnChange(Func changeTokenProducer!!, Action changeTokenConsumer!!, TState state) + public static IDisposable OnChange(Func changeTokenProducer, Action changeTokenConsumer, TState state) { + if (changeTokenProducer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer); + } + if (changeTokenConsumer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer); + } + return new ChangeTokenRegistration(changeTokenProducer, changeTokenConsumer, state); } diff --git a/src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs b/src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs index b6440d4c4a33ca..956c7bb6143a8b 100644 --- a/src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs +++ b/src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs @@ -27,8 +27,13 @@ public class CompositeChangeToken : IChangeToken /// Creates a new instance of . /// /// The list of to compose. - public CompositeChangeToken(IReadOnlyList changeTokens!!) + public CompositeChangeToken(IReadOnlyList changeTokens) { + if (changeTokens is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokens); + } + ChangeTokens = changeTokens; for (int i = 0; i < ChangeTokens.Count; i++) { diff --git a/src/libraries/Microsoft.Extensions.Primitives/src/StringValues.cs b/src/libraries/Microsoft.Extensions.Primitives/src/StringValues.cs index f50fa8292c8361..f78cfc16c5ce5e 100644 --- a/src/libraries/Microsoft.Extensions.Primitives/src/StringValues.cs +++ b/src/libraries/Microsoft.Extensions.Primitives/src/StringValues.cs @@ -366,7 +366,7 @@ private void CopyTo(string?[] array, int arrayIndex) { if (array == null) { - throw new ArgumentNullException(nameof(array)); + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (arrayIndex < 0) { diff --git a/src/libraries/Microsoft.Extensions.Primitives/src/ThrowHelper.cs b/src/libraries/Microsoft.Extensions.Primitives/src/ThrowHelper.cs index 66e8947ecad9d0..3d71f00e03c65b 100644 --- a/src/libraries/Microsoft.Extensions.Primitives/src/ThrowHelper.cs +++ b/src/libraries/Microsoft.Extensions.Primitives/src/ThrowHelper.cs @@ -90,7 +90,11 @@ internal enum ExceptionArgument value, capacity, separators, - comparisonType + comparisonType, + changeTokens, + changeTokenProducer, + changeTokenConsumer, + array, } internal enum ExceptionResource diff --git a/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs b/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs index 094b6bf351d602..119b12295f6600 100644 --- a/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs +++ b/src/libraries/Microsoft.Win32.Registry.AccessControl/src/Microsoft/Win32/RegistryAclExtensions.cs @@ -8,18 +8,33 @@ namespace Microsoft.Win32 { public static class RegistryAclExtensions { - public static RegistrySecurity GetAccessControl(this RegistryKey key!!) + public static RegistrySecurity GetAccessControl(this RegistryKey key) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + return key.GetAccessControl(); } - public static RegistrySecurity GetAccessControl(this RegistryKey key!!, AccessControlSections includeSections) + public static RegistrySecurity GetAccessControl(this RegistryKey key, AccessControlSections includeSections) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + return key.GetAccessControl(includeSections); } - public static void SetAccessControl(this RegistryKey key!!, RegistrySecurity registrySecurity) + public static void SetAccessControl(this RegistryKey key, RegistrySecurity registrySecurity) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + key.SetAccessControl(registrySecurity); } } diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs index 094a87b9c5be82..3fccbf017ec0ff 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs @@ -33,8 +33,10 @@ public static class Registry /// If the keyName is not valid, we will throw ArgumentException. /// The return value shouldn't be null. /// - private static RegistryKey GetBaseKeyFromKeyName(string keyName!!, out string subKeyName) + private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) { + ArgumentNullException.ThrowIfNull(keyName); + int i = keyName.IndexOf('\\'); int length = i != -1 ? i : keyName.Length; diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs index 4dd90defa662b2..233b7bf870e87a 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -323,8 +323,10 @@ public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineNam return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default); } - public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName!!, RegistryView view) + public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName, RegistryView view) { + ArgumentNullException.ThrowIfNull(machineName); + ValidateKeyView(view); return OpenRemoteBaseKeyCore(hKey, machineName, view); @@ -440,8 +442,10 @@ public static RegistryKey FromHandle(SafeRegistryHandle handle) return FromHandle(handle, RegistryView.Default); } - public static RegistryKey FromHandle(SafeRegistryHandle handle!!, RegistryView view) + public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view) { + ArgumentNullException.ThrowIfNull(handle); + ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); @@ -549,8 +553,10 @@ public void SetValue(string? name, object value) SetValue(name, value, RegistryValueKind.Unknown); } - public void SetValue(string? name, object value!!, RegistryValueKind valueKind) + public void SetValue(string? name, object value, RegistryValueKind valueKind) { + ArgumentNullException.ThrowIfNull(value); + if (name != null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); @@ -708,8 +714,10 @@ private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) } } - private static void ValidateKeyName(string name!!) + private static void ValidateKeyName(string name) { + ArgumentNullException.ThrowIfNull(name); + int nextSlash = name.IndexOf('\\'); int current = 0; while (nextSlash >= 0) diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index f9308292e79c2f..bcd40f574478fb 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -545,8 +545,13 @@ private static string GetXmlSerializerAssemblyName(Type type) return GetXmlSerializerAssemblyName(type, null); } - private static string GetXmlSerializerAssemblyName(Type type!!, string defaultNamespace) + private static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + return GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index 2dfbca9def9ba6..cc7fcd1fb3c071 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -516,8 +516,13 @@ private void GenerateNamespace(CodeNamespace e) GenerateNamespaceEnd(e); } - private void GenerateStatement(CodeStatement e!!) + private void GenerateStatement(CodeStatement e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); @@ -2675,8 +2680,13 @@ public void ValidateIdentifier(string value) } } - public string CreateValidIdentifier(string name!!) + public string CreateValidIdentifier(string name) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (CSharpHelpers.IsPrefixTwoUnderscore(name)) { name = "_" + name; @@ -2690,8 +2700,13 @@ public string CreateValidIdentifier(string name!!) return name; } - public string CreateEscapedIdentifier(string name!!) + public string CreateEscapedIdentifier(string name) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + return CSharpHelpers.CreateEscapedIdentifier(name); } @@ -2872,8 +2887,13 @@ private void OutputStartingBrace() } } - CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options!!, CodeCompileUnit e) + CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromDom(options, e); @@ -2884,8 +2904,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options! } } - CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options!!, string fileName) + CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromFile(options, fileName); @@ -2896,8 +2921,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options } } - CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options!!, string source) + CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromSource(options, source); @@ -2908,8 +2938,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio } } - CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options!!, string[] sources) + CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromSourceBatch(options, sources); @@ -2920,8 +2955,17 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters } } - CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options!!, string[] fileNames!!) + CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (fileNames is null) + { + throw new ArgumentNullException(nameof(fileNames)); + } + try { // Try opening the files to make sure they exists. This will throw an exception @@ -2939,8 +2983,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op } } - CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options!!, CodeCompileUnit[] ea) + CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromDomBatch(options, ea); @@ -2951,14 +3000,28 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt } } - private CompilerResults FromDom(CompilerParameters options!!, CodeCompileUnit e) + private CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + return FromDomBatch(options, new CodeCompileUnit[1] { e }); } - private static CompilerResults FromFile(CompilerParameters options!!, string fileName!!) + private static CompilerResults FromFile(CompilerParameters options, string fileName) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (fileName is null) + { + throw new ArgumentNullException(nameof(fileName)); + } + // Try opening the file to make sure it exists. This will throw an exception // if it doesn't File.OpenRead(fileName).Dispose(); @@ -2966,13 +3029,27 @@ private static CompilerResults FromFile(CompilerParameters options!!, string fil return FromFileBatch(options, new string[1] { fileName }); } - private static CompilerResults FromSource(CompilerParameters options!!, string source) + private static CompilerResults FromSource(CompilerParameters options, string source) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + return FromSourceBatch(options, new string[1] { source }); } - private CompilerResults FromDomBatch(CompilerParameters options!!, CodeCompileUnit[] ea!!) + private CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (ea is null) + { + throw new ArgumentNullException(nameof(ea)); + } + string[] filenames = new string[ea.Length]; for (int i = 0; i < ea.Length; i++) @@ -3009,8 +3086,17 @@ private static void ResolveReferencedAssemblies(CompilerParameters options, Code } } - private static CompilerResults FromSourceBatch(CompilerParameters options!!, string[] sources!!) + private static CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (sources is null) + { + throw new ArgumentNullException(nameof(sources)); + } + string[] filenames = new string[sources.Length]; for (int i = 0; i < sources.Length; i++) diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs index 4fabb5ce695162..cbc1defe51e4a3 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs @@ -20,8 +20,13 @@ public CSharpCodeProvider() _generator = new CSharpCodeGenerator(); } - public CSharpCodeProvider(IDictionary providerOptions!!) + public CSharpCodeProvider(IDictionary providerOptions) { + if (providerOptions is null) + { + throw new ArgumentNullException(nameof(providerOptions)); + } + _generator = new CSharpCodeGenerator(providerOptions); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs index b1837dc2c7b68c..8be7071ce5ccf3 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs @@ -34,8 +34,13 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return DefaultValue; } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType!!) + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { + if (destinationType is null) + { + throw new ArgumentNullException(nameof(destinationType)); + } + if (destinationType == typeof(string)) { object[] modifiers = Values; diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs index 7f67555914f70a..8c26d96945ee18 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs @@ -20,8 +20,13 @@ public VBCodeProvider() _generator = new VBCodeGenerator(); } - public VBCodeProvider(IDictionary providerOptions!!) + public VBCodeProvider(IDictionary providerOptions) { + if (providerOptions is null) + { + throw new ArgumentNullException(nameof(providerOptions)); + } + _generator = new VBCodeGenerator(providerOptions); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs index c4742449c99234..ce87cec1ec214a 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs @@ -34,8 +34,13 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return DefaultValue; } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType!!) + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { + if (destinationType is null) + { + throw new ArgumentNullException(nameof(destinationType)); + } + if (destinationType == typeof(string)) { object[] modifiers = Values; diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs index c8f40a7d1f2732..e284e13c5ee872 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs @@ -27,16 +27,26 @@ public CodeAttributeArgument this[int index] public int Add(CodeAttributeArgument value) => List.Add(value); - public void AddRange(CodeAttributeArgument[] value!!) + public void AddRange(CodeAttributeArgument[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeAttributeArgumentCollection value!!) + public void AddRange(CodeAttributeArgumentCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs index 32fe51fbef9377..581867095be7d9 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs @@ -29,16 +29,26 @@ public CodeAttributeDeclaration this[int index] public int Add(CodeAttributeDeclaration value) => List.Add(value); - public void AddRange(CodeAttributeDeclaration[] value!!) + public void AddRange(CodeAttributeDeclaration[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeAttributeDeclarationCollection value!!) + public void AddRange(CodeAttributeDeclarationCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs index 0217b111b0ff84..f84c2c6daa19be 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs @@ -27,16 +27,26 @@ public CodeCatchClause this[int index] public int Add(CodeCatchClause value) => List.Add(value); - public void AddRange(CodeCatchClause[] value!!) + public void AddRange(CodeCatchClause[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeCatchClauseCollection value!!) + public void AddRange(CodeCatchClauseCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs index 7ad005f6659a5d..82fa21f9d60f81 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs @@ -27,16 +27,26 @@ public CodeCommentStatement this[int index] public int Add(CodeCommentStatement value) => List.Add(value); - public void AddRange(CodeCommentStatement[] value!!) + public void AddRange(CodeCommentStatement[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeCommentStatementCollection value!!) + public void AddRange(CodeCommentStatementCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs index 522148078a17e0..a83e61bd1da1f4 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs @@ -27,16 +27,26 @@ public CodeDirective this[int index] public int Add(CodeDirective value) => List.Add(value); - public void AddRange(CodeDirective[] value!!) + public void AddRange(CodeDirective[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeDirectiveCollection value!!) + public void AddRange(CodeDirectiveCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs index 62a8a77c1ca742..81378ae61857ad 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs @@ -27,16 +27,26 @@ public CodeExpression this[int index] public int Add(CodeExpression value) => List.Add(value); - public void AddRange(CodeExpression[] value!!) + public void AddRange(CodeExpression[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeExpressionCollection value!!) + public void AddRange(CodeExpressionCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs index dc8163b3c97b60..10b54980c9fea2 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs @@ -27,16 +27,26 @@ public CodeNamespace this[int index] public int Add(CodeNamespace value) => List.Add(value); - public void AddRange(CodeNamespace[] value!!) + public void AddRange(CodeNamespace[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeNamespaceCollection value!!) + public void AddRange(CodeNamespaceCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs index c86444e3cb0333..ce6e6e50153912 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs @@ -36,8 +36,13 @@ public void Add(CodeNamespaceImport value) } } - public void AddRange(CodeNamespaceImport[] value!!) + public void AddRange(CodeNamespaceImport[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + foreach (CodeNamespaceImport c in value) { Add(c); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs index 933fea75089d06..1991e01236964b 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs @@ -27,16 +27,26 @@ public CodeParameterDeclarationExpression this[int index] public int Add(CodeParameterDeclarationExpression value) => List.Add(value); - public void AddRange(CodeParameterDeclarationExpression[] value!!) + public void AddRange(CodeParameterDeclarationExpression[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeParameterDeclarationExpressionCollection value!!) + public void AddRange(CodeParameterDeclarationExpressionCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs index c0ecd53ab960b8..51ceda89b44edc 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs @@ -29,16 +29,26 @@ public CodeStatement this[int index] public int Add(CodeExpression value) => Add(new CodeExpressionStatement(value)); - public void AddRange(CodeStatement[] value!!) + public void AddRange(CodeStatement[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeStatementCollection value!!) + public void AddRange(CodeStatementCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs index 19101e49e608ed..ceafd0c51eb83a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs @@ -27,16 +27,26 @@ public CodeTypeDeclaration this[int index] public int Add(CodeTypeDeclaration value) => List.Add(value); - public void AddRange(CodeTypeDeclaration[] value!!) + public void AddRange(CodeTypeDeclaration[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeTypeDeclarationCollection value!!) + public void AddRange(CodeTypeDeclarationCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs index 32683b4379c224..2d63d3a87300b6 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs @@ -27,16 +27,26 @@ public CodeTypeMember this[int index] public int Add(CodeTypeMember value) => List.Add(value); - public void AddRange(CodeTypeMember[] value!!) + public void AddRange(CodeTypeMember[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeTypeMemberCollection value!!) + public void AddRange(CodeTypeMemberCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs index 67e6c51160be39..1f403870043e9a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs @@ -29,16 +29,26 @@ public CodeTypeParameter this[int index] public void Add(string value) => Add(new CodeTypeParameter(value)); - public void AddRange(CodeTypeParameter[] value!!) + public void AddRange(CodeTypeParameter[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CodeTypeParameterCollection value!!) + public void AddRange(CodeTypeParameterCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs index e2da041b18e0a3..ab60ffc8c7a738 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs @@ -8,8 +8,13 @@ namespace System.CodeDom.Compiler { public abstract class CodeCompiler : CodeGenerator, ICodeCompiler { - CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options!!, CodeCompileUnit e) + CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromDom(options, e); @@ -20,8 +25,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options! } } - CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options!!, string fileName) + CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromFile(options, fileName); @@ -32,8 +42,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options } } - CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options!!, string source) + CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromSource(options, source); @@ -44,8 +59,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio } } - CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options!!, string[] sources) + CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromSourceBatch(options, sources); @@ -56,8 +76,17 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters } } - CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options!!, string[] fileNames!!) + CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (fileNames is null) + { + throw new ArgumentNullException(nameof(fileNames)); + } + try { // Try opening the files to make sure they exists. This will throw an exception if it doesn't @@ -74,8 +103,13 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op } } - CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options!!, CodeCompileUnit[] ea) + CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + try { return FromDomBatch(options, ea); @@ -90,13 +124,26 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt protected abstract string CompilerName { get; } - protected virtual CompilerResults FromDom(CompilerParameters options!!, CodeCompileUnit e) + protected virtual CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + return FromDomBatch(options, new CodeCompileUnit[1] { e }); } - protected virtual CompilerResults FromFile(CompilerParameters options!!, string fileName!!) + protected virtual CompilerResults FromFile(CompilerParameters options, string fileName) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (fileName is null) + { + throw new ArgumentNullException(nameof(fileName)); + } // Try opening the file to make sure it exists. This will throw an exception if it doesn't File.OpenRead(fileName).Dispose(); @@ -104,13 +151,27 @@ protected virtual CompilerResults FromFile(CompilerParameters options!!, string return FromFileBatch(options, new string[1] { fileName }); } - protected virtual CompilerResults FromSource(CompilerParameters options!!, string source) + protected virtual CompilerResults FromSource(CompilerParameters options, string source) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + return FromSourceBatch(options, new string[1] { source }); } - protected virtual CompilerResults FromDomBatch(CompilerParameters options!!, CodeCompileUnit[] ea!!) + protected virtual CompilerResults FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (ea is null) + { + throw new ArgumentNullException(nameof(ea)); + } + var filenames = new string[ea.Length]; for (int i = 0; i < ea.Length; i++) @@ -147,8 +208,17 @@ private static void ResolveReferencedAssemblies(CompilerParameters options, Code } } - protected virtual CompilerResults FromFileBatch(CompilerParameters options!!, string[] fileNames!!) + protected virtual CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (fileNames is null) + { + throw new ArgumentNullException(nameof(fileNames)); + } + throw new PlatformNotSupportedException(); } @@ -170,8 +240,17 @@ protected virtual string GetResponseFileCmdArgs(CompilerParameters options, stri return "@\"" + responseFileName + "\""; } - protected virtual CompilerResults FromSourceBatch(CompilerParameters options!!, string[] sources!!) + protected virtual CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + if (sources is null) + { + throw new ArgumentNullException(nameof(sources)); + } + var filenames = new string[sources.Length]; for (int i = 0; i < sources.Length; i++) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs index 6e984975c8c690..037dcf84df7a42 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs @@ -86,15 +86,25 @@ public static CompilerInfo GetCompilerInfo(string language) return compilerInfo; } - private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language!!) + private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) { + if (language is null) + { + throw new ArgumentNullException(nameof(language)); + } + CompilerInfo value; s_compilerLanguages.TryGetValue(language.Trim(), out value); return value; } - private static CompilerInfo GetCompilerInfoForExtensionNoThrow(string extension!!) + private static CompilerInfo GetCompilerInfoForExtensionNoThrow(string extension) { + if (extension is null) + { + throw new ArgumentNullException(nameof(extension)); + } + CompilerInfo value; s_compilerExtensions.TryGetValue(extension.Trim(), out value); return value; diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs index b7b3b24af68288..ef2ed70abe7994 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs @@ -232,8 +232,13 @@ protected void GenerateNamespaces(CodeCompileUnit e) } } - protected void GenerateTypes(CodeNamespace e!!) + protected void GenerateTypes(CodeNamespace e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + foreach (CodeTypeDeclaration c in e.Types) { if (_options.BlankLinesBetweenMembers) @@ -393,8 +398,13 @@ void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, Cod } } - public virtual void GenerateCodeFromMember(CodeTypeMember member!!, TextWriter writer, CodeGeneratorOptions options) + public virtual void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { + if (member is null) + { + throw new ArgumentNullException(nameof(member)); + } + if (_output != null) { throw new InvalidOperationException(SR.CodeGenReentrance); @@ -701,8 +711,13 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) } } - protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e!!) + protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + GenerateDirectives(e.StartDirectives); if (e.LinePragma != null) @@ -786,8 +801,13 @@ protected virtual void GenerateCompileUnit(CodeCompileUnit e) GenerateCompileUnitEnd(e); } - protected virtual void GenerateNamespace(CodeNamespace e!!) + protected virtual void GenerateNamespace(CodeNamespace e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + GenerateCommentStatements(e.Comments); GenerateNamespaceStart(e); @@ -798,8 +818,13 @@ protected virtual void GenerateNamespace(CodeNamespace e!!) GenerateNamespaceEnd(e); } - protected void GenerateNamespaceImports(CodeNamespace e!!) + protected void GenerateNamespaceImports(CodeNamespace e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + foreach (CodeNamespaceImport imp in e.Imports) { if (imp.LinePragma != null) @@ -850,8 +875,13 @@ private void GenerateProperties(CodeTypeDeclaration e) } } - protected void GenerateStatement(CodeStatement e!!) + protected void GenerateStatement(CodeStatement e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); @@ -942,16 +972,26 @@ protected void GenerateStatement(CodeStatement e!!) } } - protected void GenerateStatements(CodeStatementCollection stmts!!) + protected void GenerateStatements(CodeStatementCollection stmts) { + if (stmts is null) + { + throw new ArgumentNullException(nameof(stmts)); + } + foreach (CodeStatement stmt in stmts) { ((ICodeGenerator)this).GenerateCodeFromStatement(stmt, _output.InnerWriter, _options); } } - protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes!!) + protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationCollection attributes) { + if (attributes is null) + { + throw new ArgumentNullException(nameof(attributes)); + } + if (attributes.Count == 0) { return; @@ -993,8 +1033,13 @@ protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationColle GenerateAttributeDeclarationsEnd(attributes); } - protected virtual void OutputAttributeArgument(CodeAttributeArgument arg!!) + protected virtual void OutputAttributeArgument(CodeAttributeArgument arg) { + if (arg is null) + { + throw new ArgumentNullException(nameof(arg)); + } + if (!string.IsNullOrEmpty(arg.Name)) { OutputIdentifier(arg.Name); @@ -1244,8 +1289,13 @@ protected virtual void OutputOperator(CodeBinaryOperatorType op) } } - protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters!!) + protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters) { + if (parameters is null) + { + throw new ArgumentNullException(nameof(parameters)); + } + bool first = true; bool multiline = parameters.Count > ParameterMultilineThreshold; if (multiline) @@ -1277,8 +1327,13 @@ protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollec protected abstract void GenerateArrayCreateExpression(CodeArrayCreateExpression e); protected abstract void GenerateBaseReferenceExpression(CodeBaseReferenceExpression e); - protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e!!) + protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + bool indentedExpression = false; Output.Write('('); @@ -1328,8 +1383,13 @@ protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpres protected abstract void GenerateDelegateInvokeExpression(CodeDelegateInvokeExpression e); protected abstract void GenerateObjectCreateExpression(CodeObjectCreateExpression e); - protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e!!) + protected virtual void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpression e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.CustomAttributes.Count > 0) { OutputAttributeDeclarations(e.CustomAttributes); @@ -1340,14 +1400,24 @@ protected virtual void GenerateParameterDeclarationExpression(CodeParameterDecla OutputTypeNamePair(e.Type, e.Name); } - protected virtual void GenerateDirectionExpression(CodeDirectionExpression e!!) + protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + OutputDirection(e.Direction); GenerateExpression(e.Expression); } - protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e!!) + protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.Value == null) { Output.Write(NullToken); @@ -1421,13 +1491,23 @@ protected virtual void GenerateDefaultValueExpression(CodeDefaultValueExpression protected abstract void GenerateThisReferenceExpression(CodeThisReferenceExpression e); - protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e!!) + protected virtual void GenerateTypeReferenceExpression(CodeTypeReferenceExpression e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + OutputType(e.Type); } - protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e!!) + protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + Output.Write("typeof("); OutputType(e.Type); Output.Write(')'); @@ -1436,8 +1516,13 @@ protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e!!) protected abstract void GenerateExpressionStatement(CodeExpressionStatement e); protected abstract void GenerateIterationStatement(CodeIterationStatement e); protected abstract void GenerateThrowExceptionStatement(CodeThrowExceptionStatement e); - protected virtual void GenerateCommentStatement(CodeCommentStatement e!!) + protected virtual void GenerateCommentStatement(CodeCommentStatement e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.Comment == null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); @@ -1445,8 +1530,13 @@ protected virtual void GenerateCommentStatement(CodeCommentStatement e!!) GenerateComment(e.Comment); } - protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e!!) + protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + foreach (CodeCommentStatement comment in e) { GenerateCommentStatement(comment); @@ -1463,8 +1553,13 @@ protected virtual void GenerateCommentStatements(CodeCommentStatementCollection protected abstract void GenerateGotoStatement(CodeGotoStatement e); protected abstract void GenerateLabeledStatement(CodeLabeledStatement e); - protected virtual void GenerateSnippetStatement(CodeSnippetStatement e!!) + protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + Output.WriteLine(e.Value); } @@ -1482,16 +1577,26 @@ protected virtual void GenerateSnippetStatement(CodeSnippetStatement e!!) protected abstract void GenerateTypeStart(CodeTypeDeclaration e); protected abstract void GenerateTypeEnd(CodeTypeDeclaration e); - protected virtual void GenerateCompileUnitStart(CodeCompileUnit e!!) + protected virtual void GenerateCompileUnitStart(CodeCompileUnit e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); } } - protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e!!) + protected virtual void GenerateCompileUnitEnd(CodeCompileUnit e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + if (e.EndDirectives.Count > 0) { GenerateDirectives(e.EndDirectives); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs index e68b6c4a20ecad..78a7efb0c83811 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -407,8 +407,13 @@ private static void ValidateCommentStatement(CodeCommentStatement e) { } - private void ValidateStatement(CodeStatement e!!) + private void ValidateStatement(CodeStatement e) { + if (e is null) + { + throw new ArgumentNullException(nameof(e)); + } + ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs index a85476820e1740..91351cb6290873 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs @@ -27,16 +27,26 @@ public CompilerError this[int index] public int Add(CompilerError value) => List.Add(value); - public void AddRange(CompilerError[] value!!) + public void AddRange(CompilerError[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CompilerErrorCollection value!!) + public void AddRange(CompilerErrorCollection value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs index ac3b334a04de95..0f0edfe97e4692 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs @@ -63,8 +63,13 @@ public CodeDomProvider CreateProvider() return (CodeDomProvider)Activator.CreateInstance(CodeDomProviderType); } - public CodeDomProvider CreateProvider(IDictionary providerOptions!!) + public CodeDomProvider CreateProvider(IDictionary providerOptions) { + if (providerOptions is null) + { + throw new ArgumentNullException(nameof(providerOptions)); + } + ConstructorInfo constructor = CodeDomProviderType.GetConstructor(new Type[] { typeof(IDictionary) }); if (constructor != null) { diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs index 06c5503df3c54f..e4ec98502a72f5 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/BlockingCollection.cs @@ -173,8 +173,10 @@ public BlockingCollection(int boundedCapacity) /// The is not a positive value. /// The supplied contains more values /// than is permitted by . - public BlockingCollection(IProducerConsumerCollection collection!!, int boundedCapacity) + public BlockingCollection(IProducerConsumerCollection collection, int boundedCapacity) { + ArgumentNullException.ThrowIfNull(collection); + if (boundedCapacity < 1) { throw new ArgumentOutOfRangeException( @@ -196,8 +198,10 @@ public BlockingCollection(IProducerConsumerCollection collection!!, int bound /// The collection to use as the underlying data store. /// The argument is /// null. - public BlockingCollection(IProducerConsumerCollection collection!!) + public BlockingCollection(IProducerConsumerCollection collection) { + ArgumentNullException.ThrowIfNull(collection); + Initialize(collection, NON_BOUNDED, collection.Count); } @@ -1690,8 +1694,10 @@ IEnumerator IEnumerable.GetEnumerator() /// If the collections argument is a 0-length array or contains a /// null element. Also, if at least one of the collections has been marked complete for adds. /// If at least one of the collections has been disposed. - private static void ValidateCollectionsArray(BlockingCollection[] collections!!, bool isAddOperation) + private static void ValidateCollectionsArray(BlockingCollection[] collections, bool isAddOperation) { + ArgumentNullException.ThrowIfNull(collections); + if (collections.Length < 1) { throw new ArgumentException( @@ -1775,8 +1781,10 @@ internal sealed class BlockingCollectionDebugView /// Constructs a new debugger view object for the provided blocking collection object. /// A blocking collection to browse in the debugger. - public BlockingCollectionDebugView(BlockingCollection collection!!) + public BlockingCollectionDebugView(BlockingCollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _blockingCollection = collection; } diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs index 5a49c44c710156..38dd19d79ada51 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs @@ -53,8 +53,10 @@ public ConcurrentBag() /// cref="ConcurrentBag{T}"/>. /// is a null reference /// (Nothing in Visual Basic). - public ConcurrentBag(IEnumerable collection!!) + public ConcurrentBag(IEnumerable collection) { + ArgumentNullException.ThrowIfNull(collection); + _locals = new ThreadLocal(); WorkStealingQueue queue = GetCurrentThreadWorkStealingQueue(forceCreate: true)!; @@ -272,8 +274,10 @@ private static bool TryStealFromTo(WorkStealingQueue? startInclusive, WorkSteali /// -or- the number of elements in the source is greater than the available space from /// to the end of the destination . - public void CopyTo(T[] array!!, int index) + public void CopyTo(T[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.Collection_CopyTo_ArgumentOutOfRangeException); diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs index c170a7e46da588..c9c95e3d2ccabf 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentDictionary.cs @@ -139,9 +139,11 @@ public ConcurrentDictionary(IEqualityComparer? comparer) : this(DefaultCon /// The whose elements are copied to the new . /// The implementation to use when comparing keys. /// is a null reference (Nothing in Visual Basic). - public ConcurrentDictionary(IEnumerable> collection!!, IEqualityComparer? comparer) + public ConcurrentDictionary(IEnumerable> collection, IEqualityComparer? comparer) : this(comparer) { + ArgumentNullException.ThrowIfNull(collection); + InitializeFromCollection(collection); } @@ -160,9 +162,11 @@ public ConcurrentDictionary(IEnumerable> collection!! /// is a null reference (Nothing in Visual Basic). /// is less than 1. /// contains one or more duplicate keys. - public ConcurrentDictionary(int concurrencyLevel, IEnumerable> collection!!, IEqualityComparer? comparer) + public ConcurrentDictionary(int concurrencyLevel, IEnumerable> collection, IEqualityComparer? comparer) : this(concurrencyLevel, DefaultCapacity, growLockArray: false, comparer) { + ArgumentNullException.ThrowIfNull(collection); + InitializeFromCollection(collection); } @@ -666,8 +670,10 @@ public void Clear() /// elements in the source is greater than the available space from to /// the end of the destination . /// - void ICollection>.CopyTo(KeyValuePair[] array!!, int index) + void ICollection>.CopyTo(KeyValuePair[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ConcurrentDictionary_IndexIsNegative); @@ -1789,8 +1795,10 @@ private static void ThrowIfInvalidObjectValue(object? value) /// cref="ICollection"/> /// is greater than the available space from to the end of the destination /// . - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ConcurrentDictionary_IndexIsNegative); diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs index d3921f989d0a1d..1dd85720f0358e 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs @@ -76,8 +76,10 @@ public ConcurrentStack() /// cref="ConcurrentStack{T}"/>. /// The argument is /// null. - public ConcurrentStack(IEnumerable collection!!) + public ConcurrentStack(IEnumerable collection) { + ArgumentNullException.ThrowIfNull(collection); + InitializeFromCollection(collection); } @@ -220,8 +222,10 @@ public void Clear() /// cref="System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination . /// - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether @@ -249,8 +253,10 @@ void ICollection.CopyTo(Array array!!, int index) /// available space from to the end of the destination . /// - public void CopyTo(T[] array!!, int index) + public void CopyTo(T[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether @@ -295,8 +301,10 @@ public void Push(T item) /// be able to inject elements between the elements being pushed. Items at lower indices in /// the array will be pushed before items at higher indices. /// - public void PushRange(T[] items!!) + public void PushRange(T[] items) { + ArgumentNullException.ThrowIfNull(items); + PushRange(items, 0, items.Length); } @@ -379,8 +387,10 @@ private void PushCore(Node head, Node tail) /// /// Local helper function to validate the Pop Push range methods input /// - private static void ValidatePushPopRangeInput(T[] items!!, int startIndex, int count) + private static void ValidatePushPopRangeInput(T[] items, int startIndex, int count) { + ArgumentNullException.ThrowIfNull(items); + if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ConcurrentStack_PushPopRange_CountOutOfRange); @@ -488,8 +498,10 @@ public bool TryPop([MaybeNullWhen(false)] out T result) /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// - public int TryPopRange(T[] items!!) + public int TryPopRange(T[] items) { + ArgumentNullException.ThrowIfNull(items); + return TryPopRange(items, 0, items.Length); } diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs index b06acd06eb6e75..22910ff2835bbe 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/PartitionerStatic.cs @@ -85,8 +85,10 @@ public static class Partitioner /// /// An orderable partitioner based on the input list. /// - public static OrderablePartitioner Create(IList list!!, bool loadBalance) + public static OrderablePartitioner Create(IList list, bool loadBalance) { + ArgumentNullException.ThrowIfNull(list); + if (loadBalance) { return (new DynamicPartitionerForIList(list)); @@ -109,8 +111,10 @@ public static OrderablePartitioner Create(IList list! /// /// An orderable partitioner based on the input array. /// - public static OrderablePartitioner Create(TSource[] array!!, bool loadBalance) + public static OrderablePartitioner Create(TSource[] array, bool loadBalance) { + ArgumentNullException.ThrowIfNull(array); + // This implementation uses 'ldelem' instructions for element retrieval, rather than using a // method call. @@ -158,8 +162,10 @@ public static OrderablePartitioner Create(IEnumerable /// The ordering used in the created partitioner is determined by the natural order of the elements /// as retrieved from the source enumerable. /// - public static OrderablePartitioner Create(IEnumerable source!!, EnumerablePartitionerOptions partitionerOptions) + public static OrderablePartitioner Create(IEnumerable source, EnumerablePartitionerOptions partitionerOptions) { + ArgumentNullException.ThrowIfNull(source); + if ((partitionerOptions & (~EnumerablePartitionerOptions.NoBuffering)) != 0) throw new ArgumentOutOfRangeException(nameof(partitionerOptions)); diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs index 88c10aca600797..c385f1e2de1323 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs @@ -24,8 +24,10 @@ public CaseInsensitiveComparer() _compareInfo = CultureInfo.CurrentCulture.CompareInfo; } - public CaseInsensitiveComparer(CultureInfo culture!!) + public CaseInsensitiveComparer(CultureInfo culture) { + ArgumentNullException.ThrowIfNull(culture); + _compareInfo = culture.CompareInfo; } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs index 2d8cdeefa9c003..5b17035ca99946 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs @@ -20,8 +20,10 @@ public CaseInsensitiveHashCodeProvider() _compareInfo = CultureInfo.CurrentCulture.CompareInfo; } - public CaseInsensitiveHashCodeProvider(CultureInfo culture!!) + public CaseInsensitiveHashCodeProvider(CultureInfo culture) { + ArgumentNullException.ThrowIfNull(culture); + _compareInfo = culture.CompareInfo; } @@ -30,8 +32,10 @@ public CaseInsensitiveHashCodeProvider(CultureInfo culture!!) public static CaseInsensitiveHashCodeProvider DefaultInvariant => s_invariantCaseInsensitiveHashCodeProvider ?? (s_invariantCaseInsensitiveHashCodeProvider = new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture)); - public int GetHashCode(object obj!!) + public int GetHashCode(object obj) { + ArgumentNullException.ThrowIfNull(obj); + string? s = obj as string; return s != null ? _compareInfo.GetHashCode(s, CompareOptions.IgnoreCase) : diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs index 13ae957999cd76..fa1193c3c77e81 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs @@ -225,8 +225,9 @@ protected virtual void OnRemove(int index, object? value) { } - protected virtual void OnValidate(object value!!) + protected virtual void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); } protected virtual void OnSetComplete(int index, object? oldValue, object? newValue) diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs index 83ecd6044c8132..ced966d3aac51c 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs @@ -66,7 +66,7 @@ public Queue(int capacity, float growFactor) // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // - public Queue(ICollection col!!) : this(col.Count) + public Queue(ICollection col) : this(col?.Count ?? throw new ArgumentNullException(nameof(col))) { IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) @@ -126,8 +126,10 @@ public virtual void Clear() // CopyTo copies a collection into an Array, starting at a particular // index into the array. // - public virtual void CopyTo(Array array!!, int index) + public virtual void CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) @@ -205,8 +207,10 @@ public virtual IEnumerator GetEnumerator() // class around the queue - the caller must not use references to the // original queue. // - public static Queue Synchronized(Queue queue!!) + public static Queue Synchronized(Queue queue) { + ArgumentNullException.ThrowIfNull(queue); + return new SynchronizedQueue(queue); } @@ -482,8 +486,10 @@ internal sealed class QueueDebugView { private readonly Queue _queue; - public QueueDebugView(Queue queue!!) + public QueueDebugView(Queue queue) { + ArgumentNullException.ThrowIfNull(queue); + _queue = queue; } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs index 1af9827fdbd8c3..b1cae781a31692 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs @@ -151,8 +151,8 @@ public SortedList(IDictionary d) // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // - public SortedList(IDictionary d!!, IComparer? comparer) - : this(comparer, d.Count) + public SortedList(IDictionary d, IComparer? comparer) + : this(comparer, d?.Count ?? throw new ArgumentNullException(nameof(d))) { d.Keys.CopyTo(keys, 0); d.Values.CopyTo(values, 0); @@ -170,8 +170,10 @@ public SortedList(IDictionary d!!, IComparer? comparer) // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // - public virtual void Add(object key!!, object? value) + public virtual void Add(object key, object? value) { + ArgumentNullException.ThrowIfNull(key); + int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate_OldAndNewKeys, GetKey(i), key)); @@ -329,8 +331,10 @@ public virtual bool ContainsValue(object? value) } // Copies the values in this SortedList to an array. - public virtual void CopyTo(Array array!!, int arrayIndex) + public virtual void CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -477,8 +481,10 @@ public virtual object? this[object key] // the given key does not occur in this sorted list. Null is an invalid // key value. // - public virtual int IndexOfKey(object key!!) + public virtual int IndexOfKey(object key) { + ArgumentNullException.ThrowIfNull(key); + int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } @@ -549,8 +555,10 @@ public virtual void SetByIndex(int index, object? value) // Returns a thread-safe SortedList. // - public static SortedList Synchronized(SortedList list!!) + public static SortedList Synchronized(SortedList list) { + ArgumentNullException.ThrowIfNull(list); + return new SyncSortedList(list); } @@ -726,8 +734,10 @@ public override IList GetValueList() } } - public override int IndexOfKey(object key!!) + public override int IndexOfKey(object key) { + ArgumentNullException.ThrowIfNull(key); + lock (_root) { return _list.IndexOfKey(key); @@ -1089,8 +1099,10 @@ internal sealed class SortedListDebugView { private readonly SortedList _sortedList; - public SortedListDebugView(SortedList sortedList!!) + public SortedListDebugView(SortedList sortedList) { + ArgumentNullException.ThrowIfNull(sortedList); + _sortedList = sortedList; } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs index 1ecbd9907950da..3ea4ef1126d694 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs @@ -53,7 +53,7 @@ public Stack(int initialCapacity) // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. // - public Stack(ICollection col!!) : this(col.Count) + public Stack(ICollection col) : this(col?.Count ?? throw new ArgumentNullException(nameof(col))) { IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) @@ -112,8 +112,10 @@ public virtual bool Contains(object? obj) } // Copies the stack into an array. - public virtual void CopyTo(Array array!!, int index) + public virtual void CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) @@ -186,8 +188,10 @@ public virtual void Push(object? obj) // Returns a synchronized Stack. // - public static Stack Synchronized(Stack stack!!) + public static Stack Synchronized(Stack stack) { + ArgumentNullException.ThrowIfNull(stack); + return new SyncStack(stack); } @@ -380,8 +384,10 @@ internal sealed class StackDebugView { private readonly Stack _stack; - public StackDebugView(Stack stack!!) + public StackDebugView(Stack stack) { + ArgumentNullException.ThrowIfNull(stack); + _stack = stack; } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs index a16848cc7a3ff0..278d8884d96100 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/ListDictionary.cs @@ -30,10 +30,12 @@ public ListDictionary(IComparer? comparer) this.comparer = comparer; } - public object? this[object key!!] + public object? this[object key] { get { + ArgumentNullException.ThrowIfNull(key); + DictionaryNode? node = head; if (comparer == null) { @@ -63,6 +65,8 @@ public object? this[object key!!] } set { + ArgumentNullException.ThrowIfNull(key); + version++; DictionaryNode? last = null; DictionaryNode? node; @@ -147,8 +151,10 @@ public ICollection Values } } - public void Add(object key!!, object? value) + public void Add(object key, object? value) { + ArgumentNullException.ThrowIfNull(key); + version++; DictionaryNode? last = null; @@ -183,8 +189,10 @@ public void Clear() version++; } - public bool Contains(object key!!) + public bool Contains(object key) { + ArgumentNullException.ThrowIfNull(key); + for (DictionaryNode? node = head; node != null; node = node.next) { object oldKey = node.key; @@ -196,8 +204,10 @@ public bool Contains(object key!!) return false; } - public void CopyTo(Array array!!, int index) + public void CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); @@ -221,8 +231,10 @@ IEnumerator IEnumerable.GetEnumerator() return new NodeEnumerator(this); } - public void Remove(object key!!) + public void Remove(object key) { + ArgumentNullException.ThrowIfNull(key); + version++; DictionaryNode? last = null; DictionaryNode? node; @@ -351,8 +363,10 @@ public NodeKeyValueCollection(ListDictionary list, bool isKeys) _isKeys = isKeys; } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs index b9ad8cd08c1825..4313a8661d7018 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameObjectCollectionBase.cs @@ -363,8 +363,10 @@ public virtual int Count } } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); @@ -429,8 +431,10 @@ bool ICollection.IsSynchronized /// Returns an array of the specified type containing /// all the values in the instance. /// - protected object?[] BaseGetAllValues(Type type!!) + protected object?[] BaseGetAllValues(Type type) { + ArgumentNullException.ThrowIfNull(type); + int n = _entriesArray.Count; object?[] allValues = (object?[])Array.CreateInstance(type, n); @@ -592,8 +596,10 @@ public int Count } } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs index 10999012096be1..be3e2f3531f4d9 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/NameValueCollection.cs @@ -76,8 +76,8 @@ public NameValueCollection(int capacity, IEqualityComparer? equalityComparer) /// using the default case-insensitive hash code provider and the default /// case-insensitive comparer. /// - public NameValueCollection(int capacity, NameValueCollection col!!) - : base(capacity, col.Comparer) + public NameValueCollection(int capacity, NameValueCollection col) + : base(capacity, col != null ? col.Comparer : throw new ArgumentNullException(nameof(col))) { this.Comparer = col.Comparer; Add(col); @@ -152,8 +152,10 @@ protected void InvalidateCachedArrays() /// /// Copies the entries in the specified to the current . /// - public void Add(NameValueCollection c!!) + public void Add(NameValueCollection c) { + ArgumentNullException.ThrowIfNull(c); + InvalidateCachedArrays(); int n = c.Count; @@ -188,8 +190,10 @@ public virtual void Clear() BaseClear(); } - public void CopyTo(Array dest!!, int index) + public void CopyTo(Array dest, int index) { + ArgumentNullException.ThrowIfNull(dest); + if (dest.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(dest)); diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs index 0be13d70d9f07f..853c45a1a919bc 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/OrderedDictionary.cs @@ -260,8 +260,10 @@ public OrderedDictionary AsReadOnly() /// /// Returns true if the key exists in the table, false otherwise. /// - public bool Contains(object key!!) + public bool Contains(object key) { + ArgumentNullException.ThrowIfNull(key); + if (_objectsTable == null) { return false; @@ -384,8 +386,10 @@ IEnumerator IEnumerable.GetEnumerator() #endregion #region ISerializable implementation - public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer)); info.AddValue(ReadOnlyName, _readOnly); info.AddValue(InitCapacityName, _initialCapacity); @@ -554,8 +558,10 @@ public OrderedDictionaryKeyValueCollection(ArrayList array) private bool IsKeys => _objectsTable is not null; - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); foreach (object? o in _objects) diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs index d92f78a5515ef6..16386577856cc2 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringCollection.cs @@ -69,8 +69,10 @@ public int Add(string? value) /// /// Copies the elements of a string array to the end of the . /// - public void AddRange(string[] value!!) + public void AddRange(string[] value) { + ArgumentNullException.ThrowIfNull(value); + data.AddRange(value); } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs index 103a1ffd6926be..cbc34bfa93e878 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/StringDictionary.cs @@ -62,14 +62,18 @@ public virtual bool IsSynchronized /// /// Gets or sets the value associated with the specified key. /// - public virtual string? this[string key!!] + public virtual string? this[string key] { get { + ArgumentNullException.ThrowIfNull(key); + return (string?)contents[key.ToLowerInvariant()]; } set { + ArgumentNullException.ThrowIfNull(key); + contents[key.ToLowerInvariant()] = value; } } @@ -111,8 +115,10 @@ public virtual ICollection Values /// /// Adds an entry with the specified key and value into the StringDictionary. /// - public virtual void Add(string key!!, string? value) + public virtual void Add(string key, string? value) { + ArgumentNullException.ThrowIfNull(key); + contents.Add(key.ToLowerInvariant(), value); } @@ -127,8 +133,10 @@ public virtual void Clear() /// /// Determines if the string dictionary contains a specific key /// - public virtual bool ContainsKey(string key!!) + public virtual bool ContainsKey(string key) { + ArgumentNullException.ThrowIfNull(key); + return contents.ContainsKey(key.ToLowerInvariant()); } @@ -160,8 +168,10 @@ public virtual IEnumerator GetEnumerator() /// /// Removes the entry with the specified key from the string dictionary. /// - public virtual void Remove(string key!!) + public virtual void Remove(string key) { + ArgumentNullException.ThrowIfNull(key); + contents.Remove(key.ToLowerInvariant()); } } diff --git a/src/libraries/System.Collections.Specialized/tests/OrderedDictionary/CaseInsensitiveEqualityComparer.cs b/src/libraries/System.Collections.Specialized/tests/OrderedDictionary/CaseInsensitiveEqualityComparer.cs index b299ec73be9f02..e201d8bef6af70 100644 --- a/src/libraries/System.Collections.Specialized/tests/OrderedDictionary/CaseInsensitiveEqualityComparer.cs +++ b/src/libraries/System.Collections.Specialized/tests/OrderedDictionary/CaseInsensitiveEqualityComparer.cs @@ -25,8 +25,10 @@ internal sealed class CaseInsensitiveEqualityComparer : IEqualityComparer return x.Equals(y); } - public int GetHashCode(object obj!!) + public int GetHashCode(object obj) { + ArgumentNullException.ThrowIfNull(obj); + string s = obj as string; if (s != null) { diff --git a/src/libraries/System.Collections/src/System/Collections/BitArray.cs b/src/libraries/System.Collections/src/System/Collections/BitArray.cs index 6214eead4ce271..1c6240f4311319 100644 --- a/src/libraries/System.Collections/src/System/Collections/BitArray.cs +++ b/src/libraries/System.Collections/src/System/Collections/BitArray.cs @@ -73,8 +73,10 @@ public BitArray(int length, bool defaultValue) ** ** Exceptions: ArgumentException if bytes == null. =========================================================================*/ - public BitArray(byte[] bytes!!) + public BitArray(byte[] bytes) { + ArgumentNullException.ThrowIfNull(bytes); + // this value is chosen to prevent overflow when computing m_length. // m_length is of type int32 and is exposed as a property, so // type of m_length can't be changed to accommodate. @@ -120,8 +122,10 @@ public BitArray(byte[] bytes!!) private const uint Vector128IntCount = 4; private const uint Vector256ByteCount = 32; private const uint Vector256IntCount = 8; - public unsafe BitArray(bool[] values!!) + public unsafe BitArray(bool[] values) { + ArgumentNullException.ThrowIfNull(values); + m_array = new int[GetInt32ArrayLengthFromBitLength(values.Length)]; m_length = values.Length; @@ -186,8 +190,10 @@ public unsafe BitArray(bool[] values!!) ** ** Exceptions: ArgumentException if values == null. =========================================================================*/ - public BitArray(int[] values!!) + public BitArray(int[] values) { + ArgumentNullException.ThrowIfNull(values); + // this value is chosen to prevent overflow when computing m_length if (values.Length > int.MaxValue / BitsPerInt32) { @@ -206,8 +212,10 @@ public BitArray(int[] values!!) ** ** Exceptions: ArgumentException if bits == null. =========================================================================*/ - public BitArray(BitArray bits!!) + public BitArray(BitArray bits) { + ArgumentNullException.ThrowIfNull(bits); + int arrayLength = GetInt32ArrayLengthFromBitLength(bits.m_length); m_array = new int[arrayLength]; @@ -300,8 +308,10 @@ public void SetAll(bool value) ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ - public unsafe BitArray And(BitArray value!!) + public unsafe BitArray And(BitArray value) { + ArgumentNullException.ThrowIfNull(value); + // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with // buggy code concurrently mutating these instances in a way that could cause memory corruption, // we snapshot the arrays from both and then operate only on those snapshots, while also validating @@ -364,8 +374,10 @@ public unsafe BitArray And(BitArray value!!) ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ - public unsafe BitArray Or(BitArray value!!) + public unsafe BitArray Or(BitArray value) { + ArgumentNullException.ThrowIfNull(value); + // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with // buggy code concurrently mutating these instances in a way that could cause memory corruption, // we snapshot the arrays from both and then operate only on those snapshots, while also validating @@ -428,8 +440,10 @@ public unsafe BitArray Or(BitArray value!!) ** Exceptions: ArgumentException if value == null or ** value.Length != this.Length. =========================================================================*/ - public unsafe BitArray Xor(BitArray value!!) + public unsafe BitArray Xor(BitArray value) { + ArgumentNullException.ThrowIfNull(value); + // This method uses unsafe code to manipulate data in the BitArrays. To avoid issues with // buggy code concurrently mutating these instances in a way that could cause memory corruption, // we snapshot the arrays from both and then operate only on those snapshots, while also validating @@ -707,8 +721,10 @@ public int Length } } - public unsafe void CopyTo(Array array!!, int index) + public unsafe void CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs b/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs index ce35e1b9b8c961..d8523aab82d6db 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs @@ -13,14 +13,18 @@ public static class CollectionExtensions return dictionary.GetValueOrDefault(key, default!); } - public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary!!, TKey key, TValue defaultValue) + public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue) { + ArgumentNullException.ThrowIfNull(dictionary); + TValue? value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } - public static bool TryAdd(this IDictionary dictionary!!, TKey key, TValue value) + public static bool TryAdd(this IDictionary dictionary, TKey key, TValue value) { + ArgumentNullException.ThrowIfNull(dictionary); + if (!dictionary.ContainsKey(key)) { dictionary.Add(key, value); @@ -30,8 +34,10 @@ public static bool TryAdd(this IDictionary dictionar return false; } - public static bool Remove(this IDictionary dictionary!!, TKey key, [MaybeNullWhen(false)] out TValue value) + public static bool Remove(this IDictionary dictionary, TKey key, [MaybeNullWhen(false)] out TValue value) { + ArgumentNullException.ThrowIfNull(dictionary); + if (dictionary.TryGetValue(key, out value)) { dictionary.Remove(key); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs index e3cee881d67ca2..193867613971df 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs @@ -28,8 +28,10 @@ public LinkedList() { } - public LinkedList(IEnumerable collection!!) + public LinkedList(IEnumerable collection) { + ArgumentNullException.ThrowIfNull(collection); + foreach (T item in collection) { AddLast(item); @@ -186,8 +188,10 @@ public bool Contains(T value) return Find(value) != null; } - public void CopyTo(T[] array!!, int index) + public void CopyTo(T[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -321,8 +325,10 @@ public void RemoveLast() InternalRemoveNode(head.prev!); } - public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + // Customized serialization for LinkedList. // We need to do this because it will be too expensive to Serialize each node. // This will give us the flexiblility to change internal implementation freely in future. @@ -413,16 +419,20 @@ internal void InternalRemoveNode(LinkedListNode node) version++; } - internal static void ValidateNewNode(LinkedListNode node!!) + internal static void ValidateNewNode(LinkedListNode node) { + ArgumentNullException.ThrowIfNull(node); + if (node.list != null) { throw new InvalidOperationException(SR.LinkedListNodeIsAttached); } } - internal void ValidateNode(LinkedListNode node!!) + internal void ValidateNode(LinkedListNode node) { + ArgumentNullException.ThrowIfNull(node); + if (node.list != this) { throw new InvalidOperationException(SR.ExternalLinkedListNode); @@ -436,8 +446,10 @@ bool ICollection.IsSynchronized object ICollection.SyncRoot => this; - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs index ec88e103c3ca37..38e082bd7aa9eb 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs @@ -157,8 +157,10 @@ public PriorityQueue(IEnumerable<(TElement Element, TPriority Priority)> items) /// Constructs the heap using a heapify operation, /// which is generally faster than enqueuing individual elements sequentially. /// - public PriorityQueue(IEnumerable<(TElement Element, TPriority Priority)> items!!, IComparer? comparer) + public PriorityQueue(IEnumerable<(TElement Element, TPriority Priority)> items, IComparer? comparer) { + ArgumentNullException.ThrowIfNull(items); + _nodes = EnumerableHelpers.ToArray(items, out _size); _comparer = InitializeComparer(comparer); @@ -346,8 +348,10 @@ public TElement EnqueueDequeue(TElement element, TPriority priority) /// /// The specified argument was . /// - public void EnqueueRange(IEnumerable<(TElement Element, TPriority Priority)> items!!) + public void EnqueueRange(IEnumerable<(TElement Element, TPriority Priority)> items) { + ArgumentNullException.ThrowIfNull(items); + int count = 0; var collection = items as ICollection<(TElement Element, TPriority Priority)>; if (collection is not null && (count = collection.Count) > _nodes.Length - _size) @@ -407,8 +411,10 @@ public void EnqueueRange(IEnumerable<(TElement Element, TPriority Priority)> ite /// /// The specified argument was . /// - public void EnqueueRange(IEnumerable elements!!, TPriority priority) + public void EnqueueRange(IEnumerable elements, TPriority priority) { + ArgumentNullException.ThrowIfNull(elements); + int count; if (elements is ICollection<(TElement Element, TPriority Priority)> collection && (count = collection.Count) > _nodes.Length - _size) @@ -800,8 +806,10 @@ public sealed class UnorderedItemsCollection : IReadOnlyCollection<(TElement Ele object ICollection.SyncRoot => this; bool ICollection.IsSynchronized => false; - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueueDebugView.cs b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueueDebugView.cs index b0799caa63ab5b..d27e4ef828084b 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueueDebugView.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueueDebugView.cs @@ -10,8 +10,10 @@ internal sealed class PriorityQueueDebugView private readonly PriorityQueue _queue; private readonly bool _sort; - public PriorityQueueDebugView(PriorityQueue queue!!) + public PriorityQueueDebugView(PriorityQueue queue) { + ArgumentNullException.ThrowIfNull(queue); + _queue = queue; _sort = true; } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs index 007eb4c74b257e..ce5f3462463b9c 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs @@ -28,8 +28,10 @@ public SortedDictionary(IDictionary dictionary) : this(dictionary, { } - public SortedDictionary(IDictionary dictionary!!, IComparer? comparer) + public SortedDictionary(IDictionary dictionary, IComparer? comparer) { + ArgumentNullException.ThrowIfNull(dictionary); + var keyValuePairComparer = new KeyValuePairComparer(comparer); if (dictionary is SortedDictionary sortedDictionary && @@ -204,8 +206,10 @@ IEnumerable IReadOnlyDictionary.Values } } - public void Add(TKey key!!, TValue value) + public void Add(TKey key, TValue value) { + ArgumentNullException.ThrowIfNull(key); + _set.Add(new KeyValuePair(key, value)); } @@ -214,8 +218,10 @@ public void Clear() _set.Clear(); } - public bool ContainsKey(TKey key!!) + public bool ContainsKey(TKey key) { + ArgumentNullException.ThrowIfNull(key); + return _set.Contains(new KeyValuePair(key, default(TValue)!)); } @@ -265,13 +271,17 @@ IEnumerator> IEnumerable>. return new Enumerator(this, Enumerator.KeyValuePair); } - public bool Remove(TKey key!!) + public bool Remove(TKey key) { + ArgumentNullException.ThrowIfNull(key); + return _set.Remove(new KeyValuePair(key, default(TValue)!)); } - public bool TryGetValue(TKey key!!, [MaybeNullWhen(false)] out TValue value) + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { + ArgumentNullException.ThrowIfNull(key); + TreeSet>.Node? node = _set.FindNode(new KeyValuePair(key, default(TValue)!)); if (node == null) { @@ -351,8 +361,10 @@ ICollection IDictionary.Values } } - void IDictionary.Add(object key!!, object? value) + void IDictionary.Add(object key, object? value) { + ArgumentNullException.ThrowIfNull(key); + if (default(TValue) != null) { ArgumentNullException.ThrowIfNull(value); @@ -386,8 +398,10 @@ bool IDictionary.Contains(object key) return false; } - private static bool IsCompatibleKey(object key!!) + private static bool IsCompatibleKey(object key) { + ArgumentNullException.ThrowIfNull(key); + return (key is TKey); } @@ -536,8 +550,10 @@ public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCol { private readonly SortedDictionary _dictionary; - public KeyCollection(SortedDictionary dictionary!!) + public KeyCollection(SortedDictionary dictionary) { + ArgumentNullException.ThrowIfNull(dictionary); + _dictionary = dictionary; } @@ -556,8 +572,10 @@ IEnumerator IEnumerable.GetEnumerator() return new Enumerator(_dictionary); } - public void CopyTo(TKey[] array!!, int index) + public void CopyTo(TKey[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -571,8 +589,10 @@ public void CopyTo(TKey[] array!!, int index) _dictionary._set.InOrderTreeWalk(delegate (TreeSet>.Node node) { array[index++] = node.Item.Key; return true; }); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -704,8 +724,10 @@ public sealed class ValueCollection : ICollection, ICollection, IReadOnl { private readonly SortedDictionary _dictionary; - public ValueCollection(SortedDictionary dictionary!!) + public ValueCollection(SortedDictionary dictionary) { + ArgumentNullException.ThrowIfNull(dictionary); + _dictionary = dictionary; } @@ -724,8 +746,10 @@ IEnumerator IEnumerable.GetEnumerator() return new Enumerator(_dictionary); } - public void CopyTo(TValue[] array!!, int index) + public void CopyTo(TValue[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -739,8 +763,10 @@ public void CopyTo(TValue[] array!!, int index) _dictionary._set.InOrderTreeWalk(delegate (TreeSet>.Node node) { array[index++] = node.Item.Value; return true; }); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs index bbf4268a6985ce..da6792635feaa2 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -147,8 +147,8 @@ public SortedList(IDictionary dictionary) // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // - public SortedList(IDictionary dictionary!!, IComparer? comparer) - : this(dictionary.Count, comparer) + public SortedList(IDictionary dictionary, IComparer? comparer) + : this(dictionary?.Count ?? throw new ArgumentNullException(nameof(dictionary)), comparer) { int count = dictionary.Count; if (count != 0) @@ -177,8 +177,10 @@ public SortedList(IDictionary dictionary!!, IComparer? compa // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // - public void Add(TKey key!!, TValue value) + public void Add(TKey key, TValue value) { + ArgumentNullException.ThrowIfNull(key); + int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); @@ -261,8 +263,10 @@ public IComparer Comparer } } - void IDictionary.Add(object key!!, object? value) + void IDictionary.Add(object key, object? value) { + ArgumentNullException.ThrowIfNull(key); + if (value == null && default(TValue) != null) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); @@ -435,8 +439,10 @@ public bool ContainsValue(TValue value) } // Copies the values in this SortedList to an array. - void ICollection>.CopyTo(KeyValuePair[] array!!, int arrayIndex) + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -454,8 +460,10 @@ void ICollection>.CopyTo(KeyValuePair[] } } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -632,8 +640,10 @@ public TValue this[TKey key] // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. - public int IndexOfKey(TKey key!!) + public int IndexOfKey(TKey key) { + ArgumentNullException.ThrowIfNull(key); + int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } @@ -735,8 +745,10 @@ public void TrimExcess() } } - private static bool IsCompatibleKey(object key!!) + private static bool IsCompatibleKey(object key) { + ArgumentNullException.ThrowIfNull(key); + return (key is TKey); } @@ -1085,8 +1097,10 @@ IEnumerator IEnumerable.GetEnumerator() return new SortedListKeyEnumerator(_dict); } - public int IndexOf(TKey key!!) + public int IndexOf(TKey key) { + ArgumentNullException.ThrowIfNull(key); + int i = Array.BinarySearch(_dict.keys, 0, _dict.Count, key, _dict.comparer); if (i >= 0) return i; diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs index a076ecf4d632fb..2c3e54002e6216 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -80,9 +80,11 @@ public SortedSet(IComparer? comparer) public SortedSet(IEnumerable collection) : this(collection, Comparer.Default) { } - public SortedSet(IEnumerable collection!!, IComparer? comparer) + public SortedSet(IEnumerable collection, IComparer? comparer) : this(comparer) { + ArgumentNullException.ThrowIfNull(collection); + // These are explicit type checks in the mold of HashSet. It would have worked better with // something like an ISorted interface. (We could make this work for SortedList.Keys, etc.) SortedSet? sortedSet = collection as SortedSet; @@ -505,8 +507,10 @@ public virtual void Clear() public void CopyTo(T[] array, int index) => CopyTo(array, index, Count); - public void CopyTo(T[] array!!, int index, int count) + public void CopyTo(T[] array, int index, int count) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -536,8 +540,10 @@ public void CopyTo(T[] array!!, int index, int count) }); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -843,8 +849,10 @@ private bool HasEqualComparer(SortedSet other) #region ISet members - public void UnionWith(IEnumerable other!!) + public void UnionWith(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + SortedSet? asSorted = other as SortedSet; TreeSubSet? treeSubset = this as TreeSubSet; @@ -981,8 +989,10 @@ public void UnionWith(IEnumerable other!!) return root; } - public virtual void IntersectWith(IEnumerable other!!) + public virtual void IntersectWith(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (Count == 0) return; @@ -1061,8 +1071,10 @@ internal virtual void IntersectWithEnumerable(IEnumerable other) } } - public void ExceptWith(IEnumerable other!!) + public void ExceptWith(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (count == 0) return; @@ -1097,8 +1109,10 @@ public void ExceptWith(IEnumerable other!!) } } - public void SymmetricExceptWith(IEnumerable other!!) + public void SymmetricExceptWith(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (Count == 0) { UnionWith(other); @@ -1162,8 +1176,10 @@ private void SymmetricExceptWithSameComparer(T[] other, int count) } } - public bool IsSubsetOf(IEnumerable other!!) + public bool IsSubsetOf(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (Count == 0) { return true; @@ -1195,8 +1211,10 @@ private bool IsSubsetOfSortedSetWithSameComparer(SortedSet asSorted) return true; } - public bool IsProperSubsetOf(IEnumerable other!!) + public bool IsProperSubsetOf(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (other is ICollection c) { if (Count == 0) @@ -1217,8 +1235,10 @@ public bool IsProperSubsetOf(IEnumerable other!!) return result.UniqueCount == Count && result.UnfoundCount > 0; } - public bool IsSupersetOf(IEnumerable other!!) + public bool IsSupersetOf(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (other is ICollection c && c.Count == 0) return true; @@ -1242,8 +1262,10 @@ public bool IsSupersetOf(IEnumerable other!!) return ContainsAllElements(other); } - public bool IsProperSupersetOf(IEnumerable other!!) + public bool IsProperSupersetOf(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (Count == 0) return false; @@ -1272,8 +1294,10 @@ public bool IsProperSupersetOf(IEnumerable other!!) return result.UniqueCount < Count && result.UnfoundCount == 0; } - public bool SetEquals(IEnumerable other!!) + public bool SetEquals(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + SortedSet? asSorted = other as SortedSet; if (asSorted != null && HasEqualComparer(asSorted)) { @@ -1298,8 +1322,10 @@ public bool SetEquals(IEnumerable other!!) return result.UniqueCount == Count && result.UnfoundCount == 0; } - public bool Overlaps(IEnumerable other!!) + public bool Overlaps(IEnumerable other) { + ArgumentNullException.ThrowIfNull(other); + if (Count == 0) return false; @@ -1405,8 +1431,10 @@ private unsafe ElementCount CheckUniqueAndUnfoundElements(IEnumerable other, return result; } - public int RemoveWhere(Predicate match!!) + public int RemoveWhere(Predicate match) { + ArgumentNullException.ThrowIfNull(match); + List matches = new List(this.Count); BreadthFirstTreeWalk(n => @@ -1508,8 +1536,10 @@ internal virtual bool versionUpToDate() void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) => GetObjectData(info, context); - protected virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) + protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue(CountName, count); // This is the length of the bucket array. info.AddValue(ComparerName, comparer, typeof(IComparer)); info.AddValue(VersionName, version); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs index 7d51ad58ba2cb4..aa7a92b38f0e1a 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs @@ -48,8 +48,10 @@ public Stack(int capacity) // Fills a Stack with the contents of a particular collection. The items are // pushed onto the stack in the same order they are read by the enumerator. - public Stack(IEnumerable collection!!) + public Stack(IEnumerable collection) { + ArgumentNullException.ThrowIfNull(collection); + _array = EnumerableHelpers.ToArray(collection, out _size); } @@ -92,8 +94,10 @@ public bool Contains(T item) } // Copies the stack into an array. - public void CopyTo(T[] array!!, int arrayIndex) + public void CopyTo(T[] array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -113,8 +117,10 @@ public void CopyTo(T[] array!!, int arrayIndex) } } - void ICollection.CopyTo(Array array!!, int arrayIndex) + void ICollection.CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs b/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs index bbb5ed33c93b78..ee5f29aab66940 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs @@ -9,8 +9,10 @@ internal sealed class StackDebugView { private readonly Stack _stack; - public StackDebugView(Stack stack!!) + public StackDebugView(Stack stack) { + ArgumentNullException.ThrowIfNull(stack); + _stack = stack; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs index 52d67ed2ce5cf7..cbc0800d5cba05 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociatedMetadataTypeTypeDescriptionProvider.cs @@ -33,9 +33,11 @@ public AssociatedMetadataTypeTypeDescriptionProvider(Type type) /// The value of associatedMetadataType is null. public AssociatedMetadataTypeTypeDescriptionProvider( Type type, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type associatedMetadataType!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type associatedMetadataType) : this(type) { + ArgumentNullException.ThrowIfNull(associatedMetadataType); + _associatedMetadataType = associatedMetadataType; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs index 5f1fe3536c6338..698b95bceac465 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs @@ -12,8 +12,10 @@ namespace System.ComponentModel.DataAnnotations public class CompareAttribute : ValidationAttribute { [RequiresUnreferencedCode("The property referenced by 'otherProperty' may be trimmed. Ensure it is preserved.")] - public CompareAttribute(string otherProperty!!) : base(SR.CompareAttribute_MustMatch) + public CompareAttribute(string otherProperty) : base(SR.CompareAttribute_MustMatch) { + ArgumentNullException.ThrowIfNull(otherProperty); + OtherProperty = otherProperty; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs index 4314563f23aba3..4760db92e3d0f8 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs @@ -406,8 +406,10 @@ public virtual bool IsValid(object? value) /// is thrown when /// has not been implemented by a derived class. /// - public ValidationResult? GetValidationResult(object? value, ValidationContext validationContext!!) + public ValidationResult? GetValidationResult(object? value, ValidationContext validationContext) { + ArgumentNullException.ThrowIfNull(validationContext); + var result = IsValid(value, validationContext); // If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage @@ -471,8 +473,10 @@ public void Validate(object? value, string name) /// is thrown when /// has not been implemented by a derived class. /// - public void Validate(object? value, ValidationContext validationContext!!) + public void Validate(object? value, ValidationContext validationContext) { + ArgumentNullException.ThrowIfNull(validationContext); + ValidationResult? result = GetValidationResult(value, validationContext); if (result != null) diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs index 629c339255bd7f..d12245303887d8 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs @@ -135,8 +135,9 @@ private TypeStoreItem GetTypeStoreItem([DynamicallyAccessedMembers(TypeStoreItem /// Throws an ArgumentException of the validation context is null /// /// The context to check - private static void EnsureValidationContext(ValidationContext validationContext!!) + private static void EnsureValidationContext(ValidationContext validationContext) { + ArgumentNullException.ThrowIfNull(validationContext); } internal static bool IsPublic(PropertyInfo p) => diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs index 58163389f9a4f0..8708881796026c 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs @@ -84,8 +84,10 @@ public ValidationContext(object instance, IDictionary? items) /// /// When is null [RequiresUnreferencedCode(InstanceTypeNotStaticallyDiscovered)] - public ValidationContext(object instance!!, IServiceProvider? serviceProvider, IDictionary? items) + public ValidationContext(object instance, IServiceProvider? serviceProvider, IDictionary? items) { + ArgumentNullException.ThrowIfNull(instance); + if (serviceProvider != null) { IServiceProvider localServiceProvider = serviceProvider; diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs index 004d66ca0fde8a..a16dab0578da49 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs @@ -65,8 +65,10 @@ public ValidationResult(string? errorMessage, IEnumerable? memberNames) /// /// The validation result. /// The is null. - protected ValidationResult(ValidationResult validationResult!!) + protected ValidationResult(ValidationResult validationResult) { + ArgumentNullException.ThrowIfNull(validationResult); + ErrorMessage = validationResult.ErrorMessage; MemberNames = validationResult.MemberNames; } diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs index 53ce73aa522a13..fd1af2612280d2 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs @@ -130,9 +130,11 @@ public static bool TryValidateObject( /// on . /// [RequiresUnreferencedCode(ValidationContext.InstanceTypeNotStaticallyDiscovered)] - public static bool TryValidateObject(object instance!!, ValidationContext validationContext, + public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection? validationResults, bool validateAllProperties) { + ArgumentNullException.ThrowIfNull(instance); + if (validationContext != null && instance != validationContext.ObjectInstance) { throw new ArgumentException(SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); @@ -181,8 +183,10 @@ public static bool TryValidateObject(object instance!!, ValidationContext valida /// /// true if the object is valid, false if any validation errors are encountered. public static bool TryValidateValue(object value, ValidationContext validationContext, - ICollection? validationResults, IEnumerable validationAttributes!!) + ICollection? validationResults, IEnumerable validationAttributes) { + ArgumentNullException.ThrowIfNull(validationAttributes); + var result = true; var breakOnFirstError = validationResults == null; @@ -269,9 +273,12 @@ public static void ValidateObject(object instance, ValidationContext validationC /// /// When is found to be invalid. [RequiresUnreferencedCode(ValidationContext.InstanceTypeNotStaticallyDiscovered)] - public static void ValidateObject(object instance!!, ValidationContext validationContext!!, + public static void ValidateObject(object instance, ValidationContext validationContext, bool validateAllProperties) { + ArgumentNullException.ThrowIfNull(instance); + ArgumentNullException.ThrowIfNull(validationContext); + if (instance != validationContext.ObjectInstance) { throw new ArgumentException(SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); @@ -301,9 +308,12 @@ public static void ValidateObject(object instance!!, ValidationContext validatio /// The list of s to validate against this instance. /// When is null. /// When is found to be invalid. - public static void ValidateValue(object value, ValidationContext validationContext!!, - IEnumerable validationAttributes!!) + public static void ValidateValue(object value, ValidationContext validationContext, + IEnumerable validationAttributes) { + ArgumentNullException.ThrowIfNull(validationContext); + ArgumentNullException.ThrowIfNull(validationAttributes); + List errors = GetValidationErrors(value, validationContext, validationAttributes, false); if (errors.Count > 0) { @@ -391,8 +401,10 @@ private static void EnsureValidPropertyType(string propertyName, Type propertyTy /// [RequiresUnreferencedCode(ValidationContext.InstanceTypeNotStaticallyDiscovered)] private static List GetObjectValidationErrors(object instance, - ValidationContext validationContext!!, bool validateAllProperties, bool breakOnFirstError) + ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError) { + ArgumentNullException.ThrowIfNull(validationContext); + Debug.Assert(instance != null); // Step 1: Validate the object properties' validation attributes @@ -540,8 +552,10 @@ private static IEnumerable GetObjectPropertyValidationErrors(ob /// The collection of validation errors. /// When is null. private static List GetValidationErrors(object? value, - ValidationContext validationContext!!, IEnumerable attributes, bool breakOnFirstError) + ValidationContext validationContext, IEnumerable attributes, bool breakOnFirstError) { + ArgumentNullException.ThrowIfNull(validationContext); + var errors = new List(); ValidationError? validationError; diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs index 6ee1a534f56f6f..83747795d7b4a9 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs @@ -96,64 +96,109 @@ public PartBuilder ExportInterfaces() return ExportInterfaces(t => true, null); } - public PartBuilder ExportInterfaces(Predicate interfaceFilter!!, + public PartBuilder ExportInterfaces(Predicate interfaceFilter, Action exportConfiguration) { + if (interfaceFilter is null) + { + throw new ArgumentNullException(nameof(interfaceFilter)); + } + _interfaceExports.Add(Tuple.Create(interfaceFilter, exportConfiguration)); return this; } // Choose a property to export then configure it - public PartBuilder ExportProperties(Predicate propertyFilter!!) + public PartBuilder ExportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ExportProperties(propertyFilter, null); } - public PartBuilder ExportProperties(Predicate propertyFilter!!, + public PartBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, default(Type))); return this; } // Choose a property to export then configure it - public PartBuilder ExportProperties(Predicate propertyFilter!!) + public PartBuilder ExportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ExportProperties(propertyFilter, null); } - public PartBuilder ExportProperties(Predicate propertyFilter!!, + public PartBuilder ExportProperties(Predicate propertyFilter, Action exportConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + _propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, typeof(T))); return this; } // Choose a property to export then configure it - public PartBuilder ImportProperties(Predicate propertyFilter!!) + public PartBuilder ImportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ImportProperties(propertyFilter, null); } - public PartBuilder ImportProperties(Predicate propertyFilter!!, + public PartBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration, default(Type))); return this; } // Choose a property to export then configure it - public PartBuilder ImportProperties(Predicate propertyFilter!!) + public PartBuilder ImportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ImportProperties(propertyFilter, null); } - public PartBuilder ImportProperties(Predicate propertyFilter!!, + public PartBuilder ImportProperties(Predicate propertyFilter, Action importConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + _propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration, typeof(T))); return this; } diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs index 657c5853f72bb6..8d8de0c58d787c 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs @@ -39,8 +39,13 @@ public void ConfigureExport(PropertyInfo propertyInfo, ExportBuilder exportBuild _configureExport?.Invoke(exportBuilder); } - private static PropertyInfo SelectProperties(Expression> propertyFilter!!) + private static PropertyInfo SelectProperties(Expression> propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + Expression expr = Reduce(propertyFilter).Body; if (expr.NodeType == ExpressionType.MemberAccess) { @@ -89,8 +94,13 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportBuild } } - private void ParseSelectConstructor(Expression> constructorFilter!!) + private void ParseSelectConstructor(Expression> constructorFilter) { + if (constructorFilter is null) + { + throw new ArgumentNullException(nameof(constructorFilter)); + } + Expression expr = Reduce(constructorFilter).Body; if (expr.NodeType != ExpressionType.New) { @@ -144,8 +154,13 @@ internal PartBuilder(Predicate selectType) : base(selectType) { } - public PartBuilder SelectConstructor(Expression> constructorFilter!!) + public PartBuilder SelectConstructor(Expression> constructorFilter) { + if (constructorFilter is null) + { + throw new ArgumentNullException(nameof(constructorFilter)); + } + var adapter = new ConstructorExpressionAdapter(constructorFilter); SelectConstructor(adapter.SelectConstructor, adapter.ConfigureConstructorImports); @@ -159,9 +174,14 @@ public PartBuilder ExportProperty(Expression> propertyFilter) } public PartBuilder ExportProperty( - Expression> propertyFilter!!, + Expression> propertyFilter, Action exportConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -173,9 +193,14 @@ public PartBuilder ExportProperty(Expression> prop return ExportProperty(propertyFilter, null); } - public PartBuilder ExportProperty(Expression> propertyFilter!!, + public PartBuilder ExportProperty(Expression> propertyFilter, Action exportConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -187,9 +212,14 @@ public PartBuilder ImportProperty(Expression> propertyFilter) return ImportProperty(propertyFilter, null); } - public PartBuilder ImportProperty(Expression> propertyFilter!!, + public PartBuilder ImportProperty(Expression> propertyFilter, Action importConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); @@ -201,9 +231,14 @@ public PartBuilder ImportProperty(Expression> prop return ImportProperty(propertyFilter, null); } - public PartBuilder ImportProperty(Expression> propertyFilter!!, + public PartBuilder ImportProperty(Expression> propertyFilter, Action importConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs index fa82204739a881..0ff56463394d10 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/RegistrationBuilder.cs @@ -38,8 +38,13 @@ public PartBuilder ForTypesDerivedFrom() return partBuilder; } - public PartBuilder ForTypesDerivedFrom(Type type!!) + public PartBuilder ForTypesDerivedFrom(Type type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + var partBuilder = new PartBuilder((t) => type != t && type.IsAssignableFrom(t)); _conventions.Add(partBuilder); @@ -54,24 +59,39 @@ public PartBuilder ForType() return partBuilder; } - public PartBuilder ForType(Type type!!) + public PartBuilder ForType(Type type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + var partBuilder = new PartBuilder((t) => t == type); _conventions.Add(partBuilder); return partBuilder; } - public PartBuilder ForTypesMatching(Predicate typeFilter!!) + public PartBuilder ForTypesMatching(Predicate typeFilter) { + if (typeFilter is null) + { + throw new ArgumentNullException(nameof(typeFilter)); + } + var partBuilder = new PartBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; } - public PartBuilder ForTypesMatching(Predicate typeFilter!!) + public PartBuilder ForTypesMatching(Predicate typeFilter) { + if (typeFilter is null) + { + throw new ArgumentNullException(nameof(typeFilter)); + } + var partBuilder = new PartBuilder(typeFilter); _conventions.Add(partBuilder); diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs index 9ef2fd2f361428..bb5ad538833008 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.CollectionOfObject.cs @@ -9,8 +9,11 @@ namespace Microsoft.Internal.Collections { internal static partial class CollectionServices { - public static ICollection GetCollectionWrapper(Type itemType!!, object collectionObject!!) + public static ICollection GetCollectionWrapper(Type itemType, object collectionObject) { + ArgumentNullException.ThrowIfNull(itemType); + ArgumentNullException.ThrowIfNull(collectionObject); + var underlyingItemType = itemType.UnderlyingSystemType; if (underlyingItemType == typeof(object)) diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs index 1c0fcb03d57a89..b3f6096efc6f38 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/Collections/CollectionServices.cs @@ -56,8 +56,10 @@ public static bool IsEnumerableOfT(Type type) return null; } - public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable source!!) + public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return new ReadOnlyCollection(source.AsArray()); } @@ -163,8 +165,10 @@ public static void ForEach(this IEnumerable source, Action action) } } - public static EnumerableCardinality GetCardinality(this IEnumerable source!!) + public static EnumerableCardinality GetCardinality(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + // Cast to ICollection instead of ICollection for performance reasons. if (source is ICollection collection) { @@ -192,8 +196,10 @@ public static EnumerableCardinality GetCardinality(this IEnumerable source } } - public static Stack Copy(this Stack stack!!) + public static Stack Copy(this Stack stack) { + ArgumentNullException.ThrowIfNull(stack); + // Stack.GetEnumerator walks from top to bottom // of the stack, whereas Stack(IEnumerable) // pushes to bottom from top, so we need to reverse diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs index 10df9f5c97ba5d..afb894e0e38066 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs @@ -162,8 +162,12 @@ public static void LoadValue(this ILGenerator ilGenerator, object? value) /// /// /// - public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary!!, object key!!, object value!!) + public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, object value) { + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + Debug.Assert(ilGenerator != null); ilGenerator.Emit(OpCodes.Ldloc, dictionary); @@ -177,8 +181,12 @@ public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalB /// /// /// - public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary!!, object key!!, LocalBuilder value!!) + public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, LocalBuilder value) { + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + Debug.Assert(ilGenerator != null); ilGenerator.Emit(OpCodes.Ldloc, dictionary); @@ -191,8 +199,11 @@ public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, Local /// /// /// - public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, LocalBuilder exception!!, LocalBuilder dataStore!!) + public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, LocalBuilder exception, LocalBuilder dataStore) { + ArgumentNullException.ThrowIfNull(exception); + ArgumentNullException.ThrowIfNull(dataStore); + Debug.Assert(ilGenerator != null); ilGenerator.Emit(OpCodes.Ldloc, exception); @@ -200,8 +211,10 @@ public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, ilGenerator.Emit(OpCodes.Stloc, dataStore); } - private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable!!) + private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable) { + ArgumentNullException.ThrowIfNull(enumerable); + Debug.Assert(ilGenerator != null); // We load enumerable as an array - this is the most compact and efficient way of representing it diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs index e20f13ae89d870..8fc02e801c623a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs @@ -7,9 +7,11 @@ namespace Microsoft.Internal { internal static class LazyServices { - public static T GetNotNullValue(this Lazy lazy!!, string argument) + public static T GetNotNullValue(this Lazy lazy, string argument) where T : class { + ArgumentNullException.ThrowIfNull(lazy); + T value = lazy.Value; if (value == null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs index e3f8b040bf9419..86549e6713ae5b 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs @@ -57,13 +57,17 @@ public static bool IsVisible(this MethodInfo method) return true; } - public static string GetDisplayName(Type declaringType!!, string? name) + public static string GetDisplayName(Type declaringType, string? name) { + ArgumentNullException.ThrowIfNull(declaringType); + return declaringType.GetDisplayName() + "." + name; } - public static string GetDisplayName(this MemberInfo member!!) + public static string GetDisplayName(this MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + switch (member.MemberType) { case MemberTypes.TypeInfo: diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs index ff61848f49ae83..d5e1c3ef3b2239 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedExportDefinition.cs @@ -18,9 +18,13 @@ internal sealed class AttributedExportDefinition : ExportDefinition private IDictionary? _metadata; - public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo!!, MemberInfo member!!, ExportAttribute exportAttribute!!, Type? typeIdentityType, string contractName) + public AttributedExportDefinition(AttributedPartCreationInfo partCreationInfo, MemberInfo member, ExportAttribute exportAttribute, Type? typeIdentityType, string contractName) : base(contractName, (IDictionary?)null) { + ArgumentNullException.ThrowIfNull(partCreationInfo); + ArgumentNullException.ThrowIfNull(member); + ArgumentNullException.ThrowIfNull(exportAttribute); + _partCreationInfo = partCreationInfo; _member = member; _exportAttribute = exportAttribute; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs index 9e5d2207492f4a..04f42bf3ad47ae 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedModelDiscovery.cs @@ -24,23 +24,30 @@ internal static class AttributedModelDiscovery return new ReflectionComposablePartDefinition(creationInfo); } - public static ReflectionComposablePartDefinition CreatePartDefinition(Type type!!, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) + public static ReflectionComposablePartDefinition CreatePartDefinition(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) { + ArgumentNullException.ThrowIfNull(type); + AttributedPartCreationInfo creationInfo = new AttributedPartCreationInfo(type, partCreationPolicy, ignoreConstructorImports, origin); return new ReflectionComposablePartDefinition(creationInfo); } - public static ReflectionComposablePart CreatePart(object attributedPart!!) + public static ReflectionComposablePart CreatePart(object attributedPart) { + ArgumentNullException.ThrowIfNull(attributedPart); + // If given an instance then we want to pass the default composition options because we treat it as a shared part ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(attributedPart.GetType(), PartCreationPolicyAttribute.Shared, true, (ICompositionElement?)null); return new ReflectionComposablePart(definition, attributedPart); } - public static ReflectionComposablePart CreatePart(object attributedPart!!, ReflectionContext reflectionContext!!) + public static ReflectionComposablePart CreatePart(object attributedPart, ReflectionContext reflectionContext) { + ArgumentNullException.ThrowIfNull(attributedPart); + ArgumentNullException.ThrowIfNull(reflectionContext); + // If given an instance then we want to pass the default composition options because we treat it as a shared part var mappedType = reflectionContext.MapType(IntrospectionExtensions.GetTypeInfo(attributedPart.GetType())); if (mappedType.Assembly.ReflectionOnly) @@ -53,8 +60,11 @@ public static ReflectionComposablePart CreatePart(object attributedPart!!, Refle return CreatePart(definition, attributedPart); } - public static ReflectionComposablePart CreatePart(ComposablePartDefinition partDefinition!!, object attributedPart!!) + public static ReflectionComposablePart CreatePart(ComposablePartDefinition partDefinition, object attributedPart) { + ArgumentNullException.ThrowIfNull(partDefinition); + ArgumentNullException.ThrowIfNull(attributedPart); + return new ReflectionComposablePart((ReflectionComposablePartDefinition)partDefinition, attributedPart); } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs index 7cb235e267b4e7..4fe41238616293 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs @@ -24,8 +24,10 @@ internal sealed class AttributedPartCreationInfo : IReflectionPartCreationInfo private IEnumerable? _imports; private HashSet? _contractNamesOnNonInterfaces; - public AttributedPartCreationInfo(Type type!!, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) + public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute? partCreationPolicy, bool ignoreConstructorImports, ICompositionElement? origin) { + ArgumentNullException.ThrowIfNull(type); + _type = type; _ignoreConstructorImports = ignoreConstructorImports; _partCreationPolicy = partCreationPolicy; @@ -182,8 +184,10 @@ private CreationPolicy CreationPolicy } } - private static ConstructorInfo? SelectPartConstructor(Type type!!) + private static ConstructorInfo? SelectPartConstructor(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (type.IsAbstract) { return null; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs index 56974a4043d41b..835ac69dc589ca 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ConstraintServices.cs @@ -53,16 +53,21 @@ public static Expression> CreateConstraint(string c return constraint; } - private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter!!) + private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter) { + ArgumentNullException.ThrowIfNull(parameter); + // export.ContractName=; return Expression.Equal( Expression.Property(parameter, ConstraintServices._exportDefinitionContractNameProperty), Expression.Constant(contractName ?? string.Empty, typeof(string))); } - private static Expression? CreateMetadataConstraintBody(IEnumerable> requiredMetadata!!, ParameterExpression parameter!!) + private static Expression? CreateMetadataConstraintBody(IEnumerable> requiredMetadata, ParameterExpression parameter) { + ArgumentNullException.ThrowIfNull(requiredMetadata); + ArgumentNullException.ThrowIfNull(parameter); + Expression? body = null; foreach (KeyValuePair requiredMetadataItem in requiredMetadata) { @@ -76,8 +81,10 @@ private static Expression CreateContractConstraintBody(string contractName, Para return body; } - private static Expression CreateCreationPolicyContraint(CreationPolicy policy, ParameterExpression parameter!!) + private static Expression CreateCreationPolicyContraint(CreationPolicy policy, ParameterExpression parameter) { + ArgumentNullException.ThrowIfNull(parameter); + if (policy == CreationPolicy.Any) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -94,8 +101,11 @@ private static Expression CreateCreationPolicyContraint(CreationPolicy policy, P CreateMetadataValueEqualsExpression(parameter, policy, CompositionConstants.PartCreationPolicyMetadataName)); } - private static Expression CreateTypeIdentityContraint(string requiredTypeIdentity!!, ParameterExpression parameter!!) + private static Expression CreateTypeIdentityContraint(string requiredTypeIdentity, ParameterExpression parameter) { + ArgumentNullException.ThrowIfNull(requiredTypeIdentity); + ArgumentNullException.ThrowIfNull(parameter); + // definition.Metadata.ContainsKey(CompositionServices.ExportTypeIdentity) && // requiredTypeIdentity.Equals(definition.Metadata[CompositionConstants.ExportTypeIdentityMetadataName]); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs index fe502db6365a18..e6c4d6187dc341 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ContractNameServices.cs @@ -41,8 +41,10 @@ internal static string GetTypeIdentity(Type type) return GetTypeIdentity(type, true); } - internal static string GetTypeIdentity(Type type!!, bool formatGenericName) + internal static string GetTypeIdentity(Type type, bool formatGenericName) { + ArgumentNullException.ThrowIfNull(type); + if (!TypeIdentityCache.TryGetValue(type, out string? typeIdentity)) { if (!type.IsAbstract && type.HasBaseclassOf(typeof(Delegate))) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs index 67259b1149a227..0ba714c4822383 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ErrorBuilder.cs @@ -32,8 +32,11 @@ public static CompositionError ComposeTookTooManyIterations(int maximumNumberOfC maximumNumberOfCompositionIterations); } - public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception!!, ImportDefinition definition!!) + public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception, ImportDefinition definition) { + ArgumentNullException.ThrowIfNull(exception); + ArgumentNullException.ThrowIfNull(definition); + return CompositionError.Create( CompositionErrorId.ImportEngine_ImportCardinalityMismatch, exception.Message, @@ -41,8 +44,11 @@ public static CompositionError CreateImportCardinalityMismatch(ImportCardinality (Exception?)null); } - public static CompositionError CreatePartCannotActivate(ComposablePart part!!, Exception innerException!!) + public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException) { + ArgumentNullException.ThrowIfNull(part); + ArgumentNullException.ThrowIfNull(innerException); + ICompositionElement element = part.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCannotActivate, @@ -52,8 +58,12 @@ public static CompositionError CreatePartCannotActivate(ComposablePart part!!, E element.DisplayName); } - public static CompositionError CreatePartCannotSetImport(ComposablePart part!!, ImportDefinition definition!!, Exception innerException!!) + public static CompositionError CreatePartCannotSetImport(ComposablePart part, ImportDefinition definition, Exception innerException) { + ArgumentNullException.ThrowIfNull(part); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(innerException); + ICompositionElement element = definition.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCannotSetImport, @@ -64,8 +74,12 @@ public static CompositionError CreatePartCannotSetImport(ComposablePart part!!, part.ToElement().DisplayName); } - public static CompositionError CreateCannotGetExportedValue(ComposablePart part!!, ExportDefinition definition!!, Exception innerException!!) + public static CompositionError CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) { + ArgumentNullException.ThrowIfNull(part); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(innerException); + ICompositionElement element = definition.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCannotGetExportedValue, @@ -76,8 +90,10 @@ public static CompositionError CreateCannotGetExportedValue(ComposablePart part! part.ToElement().DisplayName); } - public static CompositionError CreatePartCycle(ComposablePart part!!) + public static CompositionError CreatePartCycle(ComposablePart part) { + ArgumentNullException.ThrowIfNull(part); + ICompositionElement element = part.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCycle, diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs index 0279e161ff7f42..97fb367565b7f3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExceptionBuilder.cs @@ -16,20 +16,26 @@ public static Exception CreateDiscoveryException(string messageFormat, params st return new InvalidOperationException(Format(messageFormat, arguments)); } - public static ArgumentException CreateContainsNullElement(string parameterName!!) + public static ArgumentException CreateContainsNullElement(string parameterName) { + ArgumentNullException.ThrowIfNull(parameterName); + string message = Format(SR.Argument_NullElement, parameterName); return new ArgumentException(message, parameterName); } - public static ObjectDisposedException CreateObjectDisposed(object instance!!) + public static ObjectDisposedException CreateObjectDisposed(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return new ObjectDisposedException(instance.GetType().ToString()); } - public static NotImplementedException CreateNotOverriddenByDerived(string memberName!!) + public static NotImplementedException CreateNotOverriddenByDerived(string memberName) { + ArgumentNullException.ThrowIfNull(memberName); + if (memberName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(memberName)), nameof(memberName)); @@ -40,8 +46,10 @@ public static NotImplementedException CreateNotOverriddenByDerived(string member return new NotImplementedException(message); } - public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName!!) + public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName) { + ArgumentNullException.ThrowIfNull(parameterName); + if (parameterName.Length == 0) { throw new ArgumentException(SR.ArgumentException_EmptyString); @@ -53,8 +61,10 @@ public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(st return new ArgumentException(message, parameterName); } - public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName!!) + public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName) { + ArgumentNullException.ThrowIfNull(parameterName); + if (parameterName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(parameterName)), nameof(parameterName)); @@ -65,14 +75,20 @@ public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(st return new ArgumentException(message, parameterName); } - public static CompositionException CreateCannotGetExportedValue(ComposablePart part!!, ExportDefinition definition!!, Exception innerException!!) + public static CompositionException CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) { + ArgumentNullException.ThrowIfNull(part); + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(innerException); + return new CompositionException( ErrorBuilder.CreateCannotGetExportedValue(part, definition, innerException)); } - public static ArgumentException CreateReflectionModelInvalidPartDefinition(string parameterName!!, Type partDefinitionType) + public static ArgumentException CreateReflectionModelInvalidPartDefinition(string parameterName, Type partDefinitionType) { + ArgumentNullException.ThrowIfNull(parameterName); + if (parameterName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(parameterName)), nameof(parameterName)); @@ -86,8 +102,10 @@ public static ArgumentException CreateReflectionModelInvalidPartDefinition(strin return new ArgumentException(SR.Format(SR.ReflectionModel_InvalidPartDefinition, partDefinitionType), parameterName); } - public static ArgumentException ExportFactory_TooManyGenericParameters(string typeName!!) + public static ArgumentException ExportFactory_TooManyGenericParameters(string typeName) { + ArgumentNullException.ThrowIfNull(typeName); + if (typeName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(typeName)), nameof(typeName)); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs index 37fe04226567d6..c4fe1472920820 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportFactoryOfT.cs @@ -7,8 +7,10 @@ public class ExportFactory { private readonly Func> _exportLifetimeContextCreator; - public ExportFactory(Func> exportLifetimeContextCreator!!) + public ExportFactory(Func> exportLifetimeContextCreator) { + ArgumentNullException.ThrowIfNull(exportLifetimeContextCreator); + _exportLifetimeContextCreator = exportLifetimeContextCreator; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs index bfbcb4b96347e8..0b7c75261dcc6e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.DisposableLazy.cs @@ -11,9 +11,11 @@ private sealed class DisposableLazy : Lazy, { private readonly IDisposable _disposable; - public DisposableLazy(Func valueFactory, TMetadataView metadataView, IDisposable disposable!!, LazyThreadSafetyMode mode) + public DisposableLazy(Func valueFactory, TMetadataView metadataView, IDisposable disposable, LazyThreadSafetyMode mode) : base(valueFactory, metadataView, mode) { + ArgumentNullException.ThrowIfNull(disposable); + _disposable = disposable; } @@ -27,9 +29,11 @@ private sealed class DisposableLazy : Lazy, IDisposable { private readonly IDisposable _disposable; - public DisposableLazy(Func valueFactory, IDisposable disposable!!, LazyThreadSafetyMode mode) + public DisposableLazy(Func valueFactory, IDisposable disposable, LazyThreadSafetyMode mode) : base(valueFactory, mode) { + ArgumentNullException.ThrowIfNull(disposable); + _disposable = disposable; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs index fff07d2d958ae6..537bb02687dd73 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ExportServices.cs @@ -23,16 +23,20 @@ internal static partial class ExportServices internal static readonly Type DefaultMetadataViewType = typeof(IDictionary); internal static readonly Type DefaultExportedValueType = typeof(object); - internal static bool IsDefaultMetadataViewType(Type metadataViewType!!) + internal static bool IsDefaultMetadataViewType(Type metadataViewType) { + ArgumentNullException.ThrowIfNull(metadataViewType); + // Consider all types that IDictionary derives from, such // as ICollection>, IEnumerable> // and IEnumerable, as default metadata view return metadataViewType.IsAssignableFrom(DefaultMetadataViewType); } - internal static bool IsDictionaryConstructorViewType(Type metadataViewType!!) + internal static bool IsDictionaryConstructorViewType(Type metadataViewType) { + ArgumentNullException.ThrowIfNull(metadataViewType); + // Does the view type have a constructor that is a Dictionary return metadataViewType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs index e07e233f5798d3..f9c70ba45ef47d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/AtomicCompositionExtensions.cs @@ -6,8 +6,10 @@ namespace System.ComponentModel.Composition.Hosting { internal static class AtomicCompositionExtensions { - internal static T GetValueAllowNull(this AtomicComposition? atomicComposition, T defaultResultAndKey!!) where T : class + internal static T GetValueAllowNull(this AtomicComposition? atomicComposition, T defaultResultAndKey) where T : class { + ArgumentNullException.ThrowIfNull(defaultResultAndKey); + return GetValueAllowNull(atomicComposition, defaultResultAndKey, defaultResultAndKey); } @@ -22,8 +24,10 @@ internal static T GetValueAllowNull(this AtomicComposition? atomicComposition return defaultResult; } - internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComposition, Action action!!) + internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComposition, Action action) { + ArgumentNullException.ThrowIfNull(action); + if (atomicComposition == null) { action(); @@ -34,8 +38,10 @@ internal static void AddRevertActionAllowNull(this AtomicComposition? atomicComp } } - internal static void AddCompleteActionAllowNull(this AtomicComposition? atomicComposition, Action action!!) + internal static void AddCompleteActionAllowNull(this AtomicComposition? atomicComposition, Action action) { + ArgumentNullException.ThrowIfNull(action); + if (atomicComposition == null) { action(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs index d79e0c71f586cb..3fbe1d1be75278 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeManager.cs @@ -13,8 +13,11 @@ internal sealed class ScopeManager : ExportProvider private readonly CompositionScopeDefinition _scopeDefinition; private readonly CatalogExportProvider _catalogExportProvider; - public ScopeManager(CatalogExportProvider catalogExportProvider!!, CompositionScopeDefinition scopeDefinition!!) + public ScopeManager(CatalogExportProvider catalogExportProvider, CompositionScopeDefinition scopeDefinition) { + ArgumentNullException.ThrowIfNull(catalogExportProvider); + ArgumentNullException.ThrowIfNull(scopeDefinition); + _scopeDefinition = scopeDefinition; _catalogExportProvider = catalogExportProvider; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs index 8ab2786e986c34..55c745587f1e77 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.cs @@ -22,8 +22,10 @@ private sealed class InnerCatalogExportProvider : ExportProvider { private readonly CatalogExportProvider _outerExportProvider; - public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider!!) + public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider) { + ArgumentNullException.ThrowIfNull(outerExportProvider); + _outerExportProvider = outerExportProvider; } @@ -562,8 +564,10 @@ private void ReleasePart(object exportedValue, CatalogPart catalogPart, AtomicCo DisposePart(exportedValue, catalogPart, atomicComposition); } - private void DisposePart(object? exportedValue, CatalogPart catalogPart!!, AtomicComposition? atomicComposition) + private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicComposition? atomicComposition) { + ArgumentNullException.ThrowIfNull(catalogPart); + if (_isDisposed) return; @@ -611,8 +615,11 @@ private void DisposePart(object? exportedValue, CatalogPart catalogPart!!, Atomi } } - private void PreventPartCollection(object exportedValue!!, ComposablePart part!!) + private void PreventPartCollection(object exportedValue, ComposablePart part) { + ArgumentNullException.ThrowIfNull(exportedValue); + ArgumentNullException.ThrowIfNull(part); + using (_lock.LockStateForWrite()) { List? partList; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs index 3e771180e8be5d..de2d80b4167616 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ComposablePartExportProvider.cs @@ -318,8 +318,10 @@ public void Compose(CompositionBatch batch) result.ThrowOnErrors(); } - private List GetUpdatedPartsList(ref CompositionBatch batch!!) + private List GetUpdatedPartsList(ref CompositionBatch batch) { + ArgumentNullException.ThrowIfNull(batch); + // Copy the current list of parts - we are about to modify it // This is an OK thing to do as this is the only method that can modify the List AND Compose can // only be executed on one thread at a time - thus two different threads cannot tramp over each other @@ -356,8 +358,10 @@ private List GetUpdatedPartsList(ref CompositionBatch batch!!) return parts; } - private void Recompose(CompositionBatch batch!!, AtomicComposition atomicComposition) + private void Recompose(CompositionBatch batch, AtomicComposition atomicComposition) { + ArgumentNullException.ThrowIfNull(batch); + // Unregister any removed component parts foreach (ComposablePart part in batch.PartsToRemove) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs index 700c77b942b8e1..d55c9584b1b787 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionBatch.SingleExportComposablePart.cs @@ -15,8 +15,10 @@ private sealed class SingleExportComposablePart : ComposablePart { private readonly Export _export; - public SingleExportComposablePart(Export export!!) + public SingleExportComposablePart(Export export) { + ArgumentNullException.ThrowIfNull(export); + _export = export; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs index 9a75cd080afe73..a95b58093492c1 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionContainer.CompositionServiceShim.cs @@ -11,8 +11,10 @@ private sealed class CompositionServiceShim : ICompositionService { private readonly CompositionContainer _innerContainer; - public CompositionServiceShim(CompositionContainer innerContainer!!) + public CompositionServiceShim(CompositionContainer innerContainer) { + ArgumentNullException.ThrowIfNull(innerContainer); + _innerContainer = innerContainer; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs index ef625dcbdd9fba..9a7cc2c7002647 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionScopeDefinition.cs @@ -184,8 +184,10 @@ public override IEnumerable> G return _catalog.GetExports(definition); } - internal IEnumerable> GetExportsFromPublicSurface(ImportDefinition definition!!) + internal IEnumerable> GetExportsFromPublicSurface(ImportDefinition definition) { + ArgumentNullException.ThrowIfNull(definition); + var exports = new List>(); foreach (var exportDefinition in PublicSurface) diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs index 2f3fe14433b246..13d9b311b21d51 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionService.cs @@ -17,8 +17,10 @@ public class CompositionService : ICompositionService, IDisposable private readonly CompositionContainer? _compositionContainer; private readonly INotifyComposablePartCatalogChanged? _notifyCatalog; - internal CompositionService(ComposablePartCatalog composablePartCatalog!!) + internal CompositionService(ComposablePartCatalog composablePartCatalog) { + ArgumentNullException.ThrowIfNull(composablePartCatalog); + _notifyCatalog = composablePartCatalog as INotifyComposablePartCatalogChanged; try { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs index 0447aef747c02b..c5c6b4b38b2c50 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CompositionServices.cs @@ -23,8 +23,10 @@ internal static class CompositionServices CompositionConstants.PartCreationPolicyMetadataName }; - internal static Type GetDefaultTypeFromMember(this MemberInfo member!!) + internal static Type GetDefaultTypeFromMember(this MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + switch (member.MemberType) { case MemberTypes.Property: @@ -56,8 +58,10 @@ internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContract } } - internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType!!, Type? memberType) + internal static Type AdjustSpecifiedTypeIdentityType(this Type specifiedContractType, Type? memberType) { + ArgumentNullException.ThrowIfNull(specifiedContractType); + if ((memberType != null) && memberType.IsGenericType && specifiedContractType.IsGenericType) { // if the memeber type is closed and the specified contract type is open and they have exatly the same number of parameters @@ -396,8 +400,10 @@ public void Add(object? item, Type? itemType) _innerList.Add(item); } - private void InferArrayType(Type itemType!!) + private void InferArrayType(Type itemType) { + ArgumentNullException.ThrowIfNull(itemType); + if (_arrayType == null) { // this is the first typed element we've been given, it sets the type of the array @@ -612,8 +618,10 @@ private static bool IsValidAttributeType(Type type) return IsValidAttributeType(type, true); } - private static bool IsValidAttributeType(Type type!!, bool arrayAllowed) + private static bool IsValidAttributeType(Type type, bool arrayAllowed) { + ArgumentNullException.ThrowIfNull(type); + // Definitions of valid attribute type taken from C# 3.0 Specification section 17.1.3. // One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort. diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs index 4b571813a5888a..d7b452fa2eb157 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.GetExportOverrides.cs @@ -794,8 +794,12 @@ private IEnumerable GetExportsCore(Type type, Type? metadataViewType, st return GetExports(importDefinition, null); } - private static ImportDefinition BuildImportDefinition(Type type!!, Type metadataViewType!!, string contractName!!, ImportCardinality cardinality) + private static ImportDefinition BuildImportDefinition(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(metadataViewType); + ArgumentNullException.ThrowIfNull(contractName); + IEnumerable> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType); IDictionary metadata = CompositionServices.GetImportMetadata(type, null); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs index 78be23bdd6704c..28ebe1fecfe64f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ExportProvider.cs @@ -205,8 +205,10 @@ protected virtual void OnExportsChanging(ExportsChangeEventArgs e) } } - private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition!!, AtomicComposition? atomicComposition, out IEnumerable? exports) + private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition? atomicComposition, out IEnumerable? exports) { + ArgumentNullException.ThrowIfNull(definition); + exports = GetExportsCore(definition, atomicComposition); var checkResult = ExportServices.CheckCardinality(definition, exports); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs index 7877e487f8a0f6..d0f2715b4e6595 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependenciesTraversal.cs @@ -17,8 +17,11 @@ internal sealed class DependenciesTraversal : IComposablePartCatalogTraversal private readonly Func _importFilter; private Dictionary>? _exportersIndex; - public DependenciesTraversal(FilteredCatalog catalog!!, Func importFilter!!) + public DependenciesTraversal(FilteredCatalog catalog, Func importFilter) { + ArgumentNullException.ThrowIfNull(catalog); + ArgumentNullException.ThrowIfNull(importFilter); + _parts = catalog._innerCatalog; _importFilter = importFilter; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs index 872d99333ad7f8..1c7f01b32e870c 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.DependentsTraversal.cs @@ -23,8 +23,11 @@ internal sealed class DependentsTraversal : IComposablePartCatalogTraversal private readonly Func _importFilter; private Dictionary>? _importersIndex; - public DependentsTraversal(FilteredCatalog catalog!!, Func importFilter!!) + public DependentsTraversal(FilteredCatalog catalog, Func importFilter) { + ArgumentNullException.ThrowIfNull(catalog); + ArgumentNullException.ThrowIfNull(importFilter); + _parts = catalog._innerCatalog; _importFilter = importFilter; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs index 8860f64133b478..10a7acc02fe2a7 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/FilteredCatalog.Traversal.cs @@ -56,8 +56,10 @@ public FilteredCatalog IncludeDependents(Func importFilt return Traverse(new DependentsTraversal(this, importFilter)); } - private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal!!) + private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal) { + ArgumentNullException.ThrowIfNull(traversal); + // we make sure that the underlyiong catalog cannot change while we are doing the trasversal // After thaty traversal is done, the freeze is lifted, and the catalog is free to change, but the changes // cannot affect partitioning @@ -75,8 +77,10 @@ private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal!!) } } - private static HashSet GetTraversalClosure(IEnumerable parts, IComposablePartCatalogTraversal traversal!!) + private static HashSet GetTraversalClosure(IEnumerable parts, IComposablePartCatalogTraversal traversal) { + ArgumentNullException.ThrowIfNull(traversal); + var traversedParts = new HashSet(); GetTraversalClosure(parts, traversedParts, traversal); return traversedParts; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs index 7ba75809e9f017..2681f60e6b4612 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.EngineContext.cs @@ -25,16 +25,20 @@ public EngineContext(ImportEngine importEngine, EngineContext? parentEngineConte _parentEngineContext = parentEngineContext; } - public void AddPartManager(PartManager part!!) + public void AddPartManager(PartManager part) { + ArgumentNullException.ThrowIfNull(part); + if (!_removedPartManagers.Remove(part)) { _addedPartManagers.Add(part); } } - public void RemovePartManager(PartManager part!!) + public void RemovePartManager(PartManager part) { + ArgumentNullException.ThrowIfNull(part); + if (!_addedPartManagers.Remove(part)) { _removedPartManagers.Add(part); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs index 57b215f82e16c4..7d6faecf7e4d7f 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportEngine.cs @@ -407,8 +407,10 @@ private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, return result; } - private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part!!, bool shouldTrackImports) + private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part, bool shouldTrackImports) { + ArgumentNullException.ThrowIfNull(part); + var result = CompositionResult.SucceededResult; // get out if the part is already composed @@ -682,8 +684,10 @@ private void StopSatisfyingImports(PartManager partManager, AtomicComposition? a return partManager; } - private EngineContext GetEngineContext(AtomicComposition atomicComposition!!) + private EngineContext GetEngineContext(AtomicComposition atomicComposition) { + ArgumentNullException.ThrowIfNull(atomicComposition); + if (!atomicComposition.TryGetValue(this, true, out EngineContext? engineContext)) { atomicComposition.TryGetValue(this, false, out EngineContext? parentContext); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs index c685134ded8a32..c57a682ce99fb3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/ImportSourceImportDefinitionHelpers.cs @@ -30,8 +30,10 @@ internal sealed class NonImportSourceImportDefinition : ContractBasedImportDefin private readonly ContractBasedImportDefinition _sourceDefinition; private IDictionary? _metadata; - public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition!!) + public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition) { + ArgumentNullException.ThrowIfNull(sourceDefinition); + _sourceDefinition = sourceDefinition; _metadata = null; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs index 50dae348243498..778ee15f4ae997 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/TypeCatalog.cs @@ -284,8 +284,10 @@ private IEnumerable PartsInternal } } - internal override IEnumerable? GetCandidateParts(ImportDefinition definition!!) + internal override IEnumerable? GetCandidateParts(ImportDefinition definition) { + ArgumentNullException.ThrowIfNull(definition); + string contractName = definition.ContractName; if (string.IsNullOrEmpty(contractName)) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs index 370486eb7fc55e..3e072d5a05d0df 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataServices.cs @@ -26,8 +26,10 @@ internal static class MetadataServices return new ReadOnlyDictionary(metadata); } - public static T? GetValue(this IDictionary metadata!!, string key) + public static T? GetValue(this IDictionary metadata, string key) { + ArgumentNullException.ThrowIfNull(metadata); + if (metadata.TryGetValue(key, out object? untypedValue) && untypedValue is T t) { return t; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs index f8188f46572e97..a295979de632d8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs @@ -88,8 +88,10 @@ private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical) return transparentProxyModuleBuilder; } - public static MetadataViewFactory GetMetadataViewFactory(Type viewType!!) + public static MetadataViewFactory GetMetadataViewFactory(Type viewType) { + ArgumentNullException.ThrowIfNull(viewType); + if (!viewType.IsInterface) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -132,8 +134,10 @@ public static MetadataViewFactory GetMetadataViewFactory(Type viewType!!) return metadataViewFactory!; } - public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory!!, IDictionary metadata) + public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory, IDictionary metadata) { + ArgumentNullException.ThrowIfNull(metadataViewFactory); + // we are simulating the Activator.CreateInstance behavior by wrapping everything in a TargetInvocationException try { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs index 85f9431381fbd6..423956e5cfb2c3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewProvider.cs @@ -12,8 +12,10 @@ namespace System.ComponentModel.Composition { internal static class MetadataViewProvider { - public static TMetadataView GetMetadataView(IDictionary metadata!!) + public static TMetadataView GetMetadataView(IDictionary metadata) { + ArgumentNullException.ThrowIfNull(metadata); + Type metadataViewType = typeof(TMetadataView); // If the Metadata dictionary is cast compatible with the passed in type @@ -121,8 +123,10 @@ public static TMetadataView GetMetadataView(IDictionary GetPureGenericParameters(this Type type!!) + internal static IList GetPureGenericParameters(this Type type) { + ArgumentNullException.ThrowIfNull(type); + if (type.IsGenericType && type.ContainsGenericParameters) { List pureGenericParameters = new List(); @@ -31,8 +33,10 @@ internal static IList GetPureGenericParameters(this Type type!!) } } - internal static int GetPureGenericArity(this Type type!!) + internal static int GetPureGenericArity(this Type type) { + ArgumentNullException.ThrowIfNull(type); + int genericArity = 0; if (type.IsGenericType && type.ContainsGenericParameters) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs index 0cda1e03db94d7..42c1e4c3b6d4ab 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/GenericSpecializationPartCreationInfo.cs @@ -29,8 +29,12 @@ internal sealed class GenericSpecializationPartCreationInfo : IReflectionPartCre private ConstructorInfo? _constructor; private readonly object _lock = new object(); - public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo!!, ReflectionComposablePartDefinition originalPart!!, Type[] specialization!!) + public GenericSpecializationPartCreationInfo(IReflectionPartCreationInfo originalPartCreationInfo, ReflectionComposablePartDefinition originalPart, Type[] specialization) { + ArgumentNullException.ThrowIfNull(originalPartCreationInfo); + ArgumentNullException.ThrowIfNull(originalPart); + ArgumentNullException.ThrowIfNull(specialization); + _originalPartCreationInfo = originalPartCreationInfo; _originalPart = originalPart; _specialization = specialization; @@ -173,8 +177,10 @@ private void BuildTables() } } - private Dictionary BuildMembersTable(List members!!) + private Dictionary BuildMembersTable(List members) { + ArgumentNullException.ThrowIfNull(members); + Dictionary membersTable = new Dictionary(); Dictionary specializedPartMembers = new Dictionary(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs index 883d19802ab21b..94927096b3f98e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportType.cs @@ -32,8 +32,10 @@ private static Dictionary?> CastSingleValueCache } } - public ImportType(Type type!!, ImportCardinality cardinality) + public ImportType(Type type, ImportCardinality cardinality) { + ArgumentNullException.ThrowIfNull(type); + _type = type; Type contractType = type; @@ -103,8 +105,11 @@ private static bool IsGenericDescendentOf(Type? type, Type baseGenericTypeDefini return IsGenericDescendentOf(type.BaseType, baseGenericTypeDefinition); } - public static bool IsDescendentOf(Type type!!, Type baseType!!) + public static bool IsDescendentOf(Type type, Type baseType) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(baseType); + if (!baseType.IsGenericTypeDefinition) { return baseType.IsAssignableFrom(type); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs index 9212785003dbff..951a518a2400c5 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingItem.cs @@ -12,8 +12,10 @@ internal abstract class ImportingItem private readonly ContractBasedImportDefinition _definition; private readonly ImportType _importType; - protected ImportingItem(ContractBasedImportDefinition definition!!, ImportType importType) + protected ImportingItem(ContractBasedImportDefinition definition, ImportType importType) { + ArgumentNullException.ThrowIfNull(definition); + _definition = definition; _importType = importType; } @@ -40,8 +42,10 @@ public ImportType ImportType } } - private object CastExportsToCollectionImportType(Export[] exports!!) + private object CastExportsToCollectionImportType(Export[] exports) { + ArgumentNullException.ThrowIfNull(exports); + // Element type could be null if the actually import type of the member is not a collection // This particular case will end up failing when we set the member. Type elementType = ImportType.ElementType ?? typeof(object); @@ -58,8 +62,10 @@ private object CastExportsToCollectionImportType(Export[] exports!!) return array; } - private object? CastExportsToSingleImportType(Export[] exports!!) + private object? CastExportsToSingleImportType(Export[] exports) { + ArgumentNullException.ThrowIfNull(exports); + if (exports.Length >= 2) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs index acf0f892b38438..7fd1b3141168f4 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ImportingMember.cs @@ -16,9 +16,11 @@ internal sealed class ImportingMember : ImportingItem { private readonly ReflectionWritableMember _member; - public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member!!, ImportType importType) + public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member, ImportType importType) : base(definition, importType) { + ArgumentNullException.ThrowIfNull(member); + _member = member; } @@ -100,8 +102,10 @@ private void EnsureWritable() } } - private void SetCollectionMemberValue(object? instance, IEnumerable values!!) + private void SetCollectionMemberValue(object? instance, IEnumerable values) { + ArgumentNullException.ThrowIfNull(values); + ICollection? collection = null; Type? itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType); if (itemType != null) @@ -113,8 +117,10 @@ private void SetCollectionMemberValue(object? instance, IEnumerable values!!) PopulateCollection(collection!, values); } - private ICollection GetNormalizedCollection(Type itemType!!, object? instance) + private ICollection GetNormalizedCollection(Type itemType, object? instance) { + ArgumentNullException.ThrowIfNull(itemType); + object? collectionObject = null; if (_member.CanRead) @@ -204,8 +210,11 @@ private void EnsureCollectionIsWritable(ICollection? collection) } } - private void PopulateCollection(ICollection collection!!, IEnumerable values!!) + private void PopulateCollection(ICollection collection, IEnumerable values) { + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(values); + try { collection.Clear(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs index fa58b846c34b04..ede92727bb51d8 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorMemberImportDefinition.cs @@ -15,10 +15,12 @@ internal sealed class PartCreatorMemberImportDefinition : ReflectionMemberImport public PartCreatorMemberImportDefinition( LazyMemberInfo importingLazyMember, ICompositionElement? origin, - ContractBasedImportDefinition productImportDefinition!!) + ContractBasedImportDefinition productImportDefinition) : base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, false, productImportDefinition.RequiredCreationPolicy, MetadataServices.EmptyMetadata, origin) { + ArgumentNullException.ThrowIfNull(productImportDefinition); + _productImportDefinition = productImportDefinition; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs index 93280fa2bc2aca..04bb344558209a 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/PartCreatorParameterImportDefinition.cs @@ -16,10 +16,12 @@ internal sealed class PartCreatorParameterImportDefinition : ReflectionParameter public PartCreatorParameterImportDefinition( Lazy importingLazyParameter, ICompositionElement? origin, - ContractBasedImportDefinition productImportDefinition!!) + ContractBasedImportDefinition productImportDefinition) : base(importingLazyParameter, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, CreationPolicy.Any, MetadataServices.EmptyMetadata, origin) { + ArgumentNullException.ThrowIfNull(productImportDefinition); + _productImportDefinition = productImportDefinition; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs index ceedd6c97bca0e..9ae09133922070 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionComposablePartDefinition.cs @@ -21,8 +21,10 @@ internal sealed class ReflectionComposablePartDefinition : ComposablePartDefinit private volatile ConstructorInfo? _constructor; private readonly object _lock = new object(); - public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo!!) + public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo) { + ArgumentNullException.ThrowIfNull(creationInfo); + _creationInfo = creationInfo; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs index 4dc59dd2b64f60..cc21bf792e3fc3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionExtensions.cs @@ -41,8 +41,10 @@ public static ReflectionMember ToReflectionMember(this LazyMemberInfo lazyMember } } - public static LazyMemberInfo ToLazyMember(this MemberInfo member!!) + public static LazyMemberInfo ToLazyMember(this MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + if (member.MemberType == MemberTypes.Property) { PropertyInfo? property = member as PropertyInfo; @@ -76,8 +78,10 @@ public static ReflectionWritableMember ToReflectionWriteableMember(this LazyMemb return reflectionMember; } - public static ReflectionProperty ToReflectionProperty(this PropertyInfo property!!) + public static ReflectionProperty ToReflectionProperty(this PropertyInfo property) { + ArgumentNullException.ThrowIfNull(property); + return CreateReflectionProperty(property.GetGetMethod(true)!, property.GetSetMethod(true)!); } @@ -91,8 +95,10 @@ public static ReflectionProperty CreateReflectionProperty(MethodInfo getMethod, return new ReflectionProperty(getMethod, setMethod); } - public static ReflectionParameter ToReflectionParameter(this ParameterInfo parameter!!) + public static ReflectionParameter ToReflectionParameter(this ParameterInfo parameter) { + ArgumentNullException.ThrowIfNull(parameter); + return new ReflectionParameter(parameter); } @@ -106,18 +112,24 @@ public static ReflectionMethod ToReflectionMethod(this MethodInfo method) return new ReflectionMethod(method); } - public static ReflectionField ToReflectionField(this FieldInfo field!!) + public static ReflectionField ToReflectionField(this FieldInfo field) { + ArgumentNullException.ThrowIfNull(field); + return new ReflectionField(field); } - public static ReflectionType ToReflectionType(this Type type!!) + public static ReflectionType ToReflectionType(this Type type) { + ArgumentNullException.ThrowIfNull(type); + return new ReflectionType(type); } - public static ReflectionWritableMember ToReflectionWritableMember(this MemberInfo member!!) + public static ReflectionWritableMember ToReflectionWritableMember(this MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + if (member.MemberType == MemberTypes.Property) { return ((PropertyInfo)member).ToReflectionProperty(); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs index 81283f0f124bd7..e3664c2db6bcf1 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs @@ -10,8 +10,10 @@ internal sealed class ReflectionField : ReflectionWritableMember { private readonly FieldInfo _field; - public ReflectionField(FieldInfo field!!) + public ReflectionField(FieldInfo field) { + ArgumentNullException.ThrowIfNull(field); + _field = field; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs index 12a2a3af79b140..f2b73d792e0f81 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs @@ -14,8 +14,10 @@ internal sealed class ReflectionMemberExportDefinition : ExportDefinition, IComp private readonly ICompositionElement? _origin; private IDictionary? _metadata; - public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition!!, ICompositionElement? origin) + public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement? origin) { + ArgumentNullException.ThrowIfNull(exportDefinition); + _member = member; _exportDefinition = exportDefinition; _origin = origin; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs index 8ea838bff2a591..7eefe2f948e829 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberImportDefinition.cs @@ -13,7 +13,7 @@ internal class ReflectionMemberImportDefinition : ReflectionImportDefinition public ReflectionMemberImportDefinition( LazyMemberInfo importingLazyMember, - string contractName!!, + string contractName, string? requiredTypeIdentity, IEnumerable>? requiredMetadata, ImportCardinality cardinality, @@ -24,6 +24,8 @@ public ReflectionMemberImportDefinition( ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin) { + ArgumentNullException.ThrowIfNull(contractName); + _importingLazyMember = importingLazyMember; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs index 9484b9ec86ffb1..0befca484d8ef3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMethod.cs @@ -10,8 +10,10 @@ internal sealed partial class ReflectionMethod : ReflectionMember { private readonly MethodInfo _method; - public ReflectionMethod(MethodInfo method!!) + public ReflectionMethod(MethodInfo method) { + ArgumentNullException.ThrowIfNull(method); + _method = method; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs index 8719590128f726..3c350175f78984 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServices.cs @@ -325,13 +325,15 @@ internal sealed class ReflectionPartCreationInfo : IReflectionPartCreationInfo private readonly bool _isDisposalRequired; public ReflectionPartCreationInfo( - Lazy partType!!, + Lazy partType, bool isDisposalRequired, Lazy>? imports, Lazy>? exports, Lazy>? metadata, ICompositionElement? origin) { + ArgumentNullException.ThrowIfNull(partType); + _partType = partType; _isDisposalRequired = isDisposalRequired; _imports = imports; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs index b7f7b9b6a6e168..81ed73e58882ba 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameter.cs @@ -11,8 +11,10 @@ internal sealed class ReflectionParameter : ReflectionItem { private readonly ParameterInfo _parameter; - public ReflectionParameter(ParameterInfo parameter!!) + public ReflectionParameter(ParameterInfo parameter) { + ArgumentNullException.ThrowIfNull(parameter); + _parameter = parameter; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs index bb8241f9554f59..3752bb1c0f76c9 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionParameterImportDefinition.cs @@ -14,7 +14,7 @@ internal class ReflectionParameterImportDefinition : ReflectionImportDefinition private readonly Lazy _importingLazyParameter; public ReflectionParameterImportDefinition( - Lazy importingLazyParameter!!, + Lazy importingLazyParameter, string contractName, string? requiredTypeIdentity, IEnumerable>? requiredMetadata, @@ -24,6 +24,8 @@ public ReflectionParameterImportDefinition( ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, metadata, origin) { + ArgumentNullException.ThrowIfNull(importingLazyParameter); + _importingLazyParameter = importingLazyParameter; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs index 9d3659fadf4c1d..02cd247a7db097 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionType.cs @@ -9,8 +9,10 @@ internal sealed class ReflectionType : ReflectionMember { private readonly Type _type; - public ReflectionType(Type type!!) + public ReflectionType(Type type) { + ArgumentNullException.ThrowIfNull(type); + _type = type; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs b/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs index 08105a1d139d87..6dcf3ba6079581 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/Composition/Diagnostics/CompositionTrace.cs @@ -12,8 +12,10 @@ namespace System.Composition.Diagnostics { internal static class CompositionTrace { - internal static void PartDefinitionResurrected(ComposablePartDefinition definition!!) + internal static void PartDefinitionResurrected(ComposablePartDefinition definition) { + ArgumentNullException.ThrowIfNull(definition); + if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Rejection_DefinitionResurrected, @@ -22,8 +24,11 @@ internal static void PartDefinitionResurrected(ComposablePartDefinition definiti } } - internal static void PartDefinitionRejected(ComposablePartDefinition definition!!, ChangeRejectedException exception!!) + internal static void PartDefinitionRejected(ComposablePartDefinition definition, ChangeRejectedException exception) { + ArgumentNullException.ThrowIfNull(definition); + ArgumentNullException.ThrowIfNull(exception); + if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Rejection_DefinitionRejected, @@ -33,8 +38,12 @@ internal static void PartDefinitionRejected(ComposablePartDefinition definition! } } - internal static void AssemblyLoadFailed(DirectoryCatalog catalog!!, string fileName!!, Exception exception!!) + internal static void AssemblyLoadFailed(DirectoryCatalog catalog, string fileName, Exception exception) { + ArgumentNullException.ThrowIfNull(catalog); + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(exception); + if (fileName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(fileName)), nameof(fileName)); @@ -50,8 +59,10 @@ internal static void AssemblyLoadFailed(DirectoryCatalog catalog!!, string fileN } } - internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type!!) + internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute, @@ -60,8 +71,11 @@ internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type! } } - internal static void DefinitionMismatchedExportArity(Type type!!, MemberInfo member!!) + internal static void DefinitionMismatchedExportArity(Type type, MemberInfo member) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(member); + if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionMismatchedExportArity, @@ -70,8 +84,10 @@ internal static void DefinitionMismatchedExportArity(Type type!!, MemberInfo mem } } - internal static void DefinitionContainsNoExports(Type type!!) + internal static void DefinitionContainsNoExports(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionContainsNoExports, @@ -80,8 +96,10 @@ internal static void DefinitionContainsNoExports(Type type!!) } } - internal static void MemberMarkedWithMultipleImportAndImportMany(ReflectionItem item!!) + internal static void MemberMarkedWithMultipleImportAndImportMany(ReflectionItem item) { + ArgumentNullException.ThrowIfNull(item); + if (CompositionTraceSource.CanWriteError) { CompositionTraceSource.WriteError(CompositionTraceId.Discovery_MemberMarkedWithMultipleImportAndImportMany, diff --git a/src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/ConstraintParser.cs b/src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/ConstraintParser.cs index 9543968fb86d16..2d17f8e25ee3dd 100644 --- a/src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/ConstraintParser.cs +++ b/src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/ConstraintParser.cs @@ -134,8 +134,11 @@ private static bool TryParseContractNameFromEqualsExpression(Expression left, Ex return true; } - private static bool TryParseExpressionAsMetadataConstraintBody(Expression expression!!, Expression parameter!!, out string requiredMetadataKey, out Type requiredMetadataType) + private static bool TryParseExpressionAsMetadataConstraintBody(Expression expression, Expression parameter, out string requiredMetadataKey, out Type requiredMetadataType) { + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(parameter); + requiredMetadataKey = null; requiredMetadataType = null; @@ -208,9 +211,11 @@ private static bool TryParseExpressionAsMetadataConstraintBody(Expression expres return true; } - private static bool TryParseConstant(ConstantExpression constant!!, out T result) + private static bool TryParseConstant(ConstantExpression constant, out T result) where T : class { + ArgumentNullException.ThrowIfNull(constant); + if (constant.Type == typeof(T) && constant.Value != null) { result = (T)constant.Value; diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/Design/Serialization/DesignerSerializerAttribute.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/Design/Serialization/DesignerSerializerAttribute.cs index 2082564bbffaff..4b13415342c4a5 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/Design/Serialization/DesignerSerializerAttribute.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/Design/Serialization/DesignerSerializerAttribute.cs @@ -16,8 +16,11 @@ public sealed class DesignerSerializerAttribute : Attribute /// /// Creates a new designer serialization attribute. /// - public DesignerSerializerAttribute(Type serializerType!!, Type baseSerializerType!!) + public DesignerSerializerAttribute(Type serializerType, Type baseSerializerType) { + ArgumentNullException.ThrowIfNull(serializerType); + ArgumentNullException.ThrowIfNull(baseSerializerType); + SerializerTypeName = serializerType.AssemblyQualifiedName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; } @@ -25,8 +28,10 @@ public DesignerSerializerAttribute(Type serializerType!!, Type baseSerializerTyp /// /// Creates a new designer serialization attribute. /// - public DesignerSerializerAttribute(string? serializerTypeName, Type baseSerializerType!!) + public DesignerSerializerAttribute(string? serializerTypeName, Type baseSerializerType) { + ArgumentNullException.ThrowIfNull(baseSerializerType); + SerializerTypeName = serializerTypeName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; } diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/DesignerAttribute.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/DesignerAttribute.cs index b78fb24b15721a..0b4fef2df2dcf1 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/DesignerAttribute.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/DesignerAttribute.cs @@ -17,8 +17,10 @@ public sealed class DesignerAttribute : Attribute /// Initializes a new instance of the class using the name of the type that /// provides design-time services. /// - public DesignerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerTypeName!!) + public DesignerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerTypeName) { + ArgumentNullException.ThrowIfNull(designerTypeName); + DesignerTypeName = designerTypeName; DesignerBaseTypeName = "System.ComponentModel.Design.IDesigner, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } @@ -27,8 +29,10 @@ public DesignerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTy /// Initializes a new instance of the class using the type that provides /// design-time services. /// - public DesignerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerType!!) + public DesignerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerType) { + ArgumentNullException.ThrowIfNull(designerType); + DesignerTypeName = designerType.AssemblyQualifiedName!; DesignerBaseTypeName = "System.ComponentModel.Design.IDesigner, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } @@ -38,9 +42,11 @@ public DesignerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTy /// base class for the designer. /// public DesignerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerTypeName!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerTypeName, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerBaseTypeName) { + ArgumentNullException.ThrowIfNull(designerTypeName); + DesignerTypeName = designerTypeName; DesignerBaseTypeName = designerBaseTypeName; } @@ -50,9 +56,12 @@ public DesignerAttribute( /// class and the base class for the designer. /// public DesignerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerTypeName!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerBaseType!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string designerTypeName, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerBaseType) { + ArgumentNullException.ThrowIfNull(designerTypeName); + ArgumentNullException.ThrowIfNull(designerBaseType); + DesignerTypeName = designerTypeName; DesignerBaseTypeName = designerBaseType.AssemblyQualifiedName!; } @@ -62,9 +71,12 @@ public DesignerAttribute( /// designer base class. /// public DesignerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerType!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerBaseType!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type designerBaseType) { + ArgumentNullException.ThrowIfNull(designerType); + ArgumentNullException.ThrowIfNull(designerBaseType); + DesignerTypeName = designerType.AssemblyQualifiedName!; DesignerBaseTypeName = designerBaseType.AssemblyQualifiedName!; } diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EditorAttribute.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EditorAttribute.cs index 6addfb6f065dea..012038a5d4957b 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EditorAttribute.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EditorAttribute.cs @@ -28,9 +28,11 @@ public EditorAttribute() /// name of the editor. /// public EditorAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string? baseTypeName) { + ArgumentNullException.ThrowIfNull(typeName); + EditorTypeName = typeName; EditorBaseTypeName = baseTypeName; } @@ -39,9 +41,12 @@ public EditorAttribute( /// Initializes a new instance of the class. /// public EditorAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type baseType!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type baseType) { + ArgumentNullException.ThrowIfNull(typeName); + ArgumentNullException.ThrowIfNull(baseType); + EditorTypeName = typeName; EditorBaseTypeName = baseType.AssemblyQualifiedName; } @@ -50,9 +55,12 @@ public EditorAttribute( /// Initializes a new instance of the class. /// public EditorAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type baseType!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type baseType) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(baseType); + EditorTypeName = type.AssemblyQualifiedName!; EditorBaseTypeName = baseType.AssemblyQualifiedName; } diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs index 40bd1c903b01f0..b59376691ccced 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs @@ -69,8 +69,10 @@ public void AddHandler(object key, Delegate? value) } } - public void AddHandlers(EventHandlerList listToAddFrom!!) + public void AddHandlers(EventHandlerList listToAddFrom) { + ArgumentNullException.ThrowIfNull(listToAddFrom); + ListEntry? currentListEntry = listToAddFrom._head; while (currentListEntry != null) { diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/InvalidEnumArgumentException.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/InvalidEnumArgumentException.cs index da48222cbfcba1..567e6a7408cb8a 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/InvalidEnumArgumentException.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/InvalidEnumArgumentException.cs @@ -43,12 +43,13 @@ public InvalidEnumArgumentException(string? message, Exception? innerException) /// class with a message generated from the argument, invalid value, and /// enumeration class. /// - public InvalidEnumArgumentException(string? argumentName, int invalidValue, Type enumClass!!) + public InvalidEnumArgumentException(string? argumentName, int invalidValue, Type enumClass) : base(SR.Format(SR.InvalidEnumArgument, argumentName, invalidValue, - enumClass.Name), argumentName) + enumClass?.Name), argumentName) { + ArgumentNullException.ThrowIfNull(enumClass); } /// diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs b/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs index c8920bb7c00f3e..899919655fb8b5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/MS/Internal/Xml/Linq/ComponentModel/XComponentModel.cs @@ -500,8 +500,11 @@ internal sealed class XDeferredAxis : IEnumerable, IEnumerable where T : X internal XElement element; internal XName? name; - public XDeferredAxis(Func> func!!, XElement element!!, XName? name) + public XDeferredAxis(Func> func, XElement element, XName? name) { + ArgumentNullException.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(element); + _func = func; this.element = element; this.name = name; @@ -542,8 +545,11 @@ internal sealed class XDeferredSingleton where T : XObject internal XElement element; internal XName? name; - public XDeferredSingleton(Func func!!, XElement element!!, XName? name) + public XDeferredSingleton(Func func, XElement element, XName? name) { + ArgumentNullException.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(element); + _func = func; this.element = element; this.name = name; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs index df35395f255337..56e81785039405 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs @@ -58,8 +58,10 @@ protected AttributeCollection() : this(Array.Empty()) /// /// Creates a new AttributeCollection from an existing AttributeCollection /// - public static AttributeCollection FromExisting(AttributeCollection existing!!, params Attribute[]? newAttributes) + public static AttributeCollection FromExisting(AttributeCollection existing, params Attribute[]? newAttributes) { + ArgumentNullException.ThrowIfNull(existing); + if (newAttributes == null) { newAttributes = Array.Empty(); @@ -125,10 +127,12 @@ public static AttributeCollection FromExisting(AttributeCollection existing!!, p /// /// Gets the attribute with the specified type. /// - public virtual Attribute? this[[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] Type attributeType!!] + public virtual Attribute? this[[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] Type attributeType] { get { + ArgumentNullException.ThrowIfNull(attributeType); + lock (s_internalSyncObject) { // 2 passes here for perf. Really! first pass, we just @@ -242,8 +246,10 @@ public bool Contains(Attribute[]? attributes) /// Returns the default value for an attribute. This uses the following heuristic: /// 1. It looks for a public static field named "Default". /// - protected Attribute? GetDefaultAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] Type attributeType!!) + protected Attribute? GetDefaultAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] Type attributeType) { + ArgumentNullException.ThrowIfNull(attributeType); + lock (s_internalSyncObject) { if (s_defaultAttributes == null) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs index 3c9f22c6572dbe..efa5335f10a76e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs @@ -13,16 +13,21 @@ public class AttributeProviderAttribute : Attribute /// /// Creates a new AttributeProviderAttribute object. /// - public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName!!) + public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName) { + ArgumentNullException.ThrowIfNull(typeName); + TypeName = typeName; } /// /// Creates a new AttributeProviderAttribute object. /// - public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName!!, string propertyName!!) + public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName, string propertyName) { + ArgumentNullException.ThrowIfNull(typeName); + ArgumentNullException.ThrowIfNull(propertyName); + TypeName = typeName; PropertyName = propertyName; } @@ -30,8 +35,10 @@ public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberType /// /// Creates a new AttributeProviderAttribute object. /// - public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] Type type!!) + public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] Type type) { + ArgumentNullException.ThrowIfNull(type); + TypeName = type.AssemblyQualifiedName; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs index 6c6edc5814e1dc..3f3fc35cb28973 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs @@ -90,8 +90,10 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source /// /// Converts the given value object to the destination type. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string) && value != null && TargetType.IsInstanceOfType(value)) { if (culture == null) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs index efb6eb8fb41cc3..1a03f04f4895a9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs @@ -63,8 +63,11 @@ private CultureInfo? NeutralResourcesCulture /// property the resource will be ignored. /// [RequiresUnreferencedCode("The Type of value cannot be statically discovered.")] - public virtual void ApplyResources(object value!!, string objectName!!, CultureInfo? culture) + public virtual void ApplyResources(object value, string objectName, CultureInfo? culture) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(objectName); + if (culture == null) { culture = CultureInfo.CurrentUICulture; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs index 3617a233e79bca..3c32c1ee6a3f67 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs @@ -217,8 +217,10 @@ private void Remove(IComponent? component, bool preserveSite) /// components in the container. /// [RequiresUnreferencedCode("The Type of components in the container cannot be statically discovered.")] - protected virtual void ValidateName(IComponent component!!, string? name) + protected virtual void ValidateName(IComponent component, string? name) { + ArgumentNullException.ThrowIfNull(component); + if (name != null) { for (int i = 0; i < Math.Min(_siteCount, _sites!.Length); i++) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs index f3877a040f0438..20787a19e4b1bd 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs @@ -29,8 +29,10 @@ public class CultureInfoConverter : TypeConverter /// /// Retrieves the Name for a input CultureInfo. /// - protected virtual string GetCultureName(CultureInfo culture!!) + protected virtual string GetCultureName(CultureInfo culture) { + ArgumentNullException.ThrowIfNull(culture); + return culture.Name; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index b39b1b67472e3f..ba0efec8f371c3 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -32,8 +32,11 @@ public DesignerOptionCollection Options /// anything into the component parameter of the property descriptor will be /// ignored and the value object will be substituted. /// - protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent!!, string name!!, object value) + protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent, string name, object value) { + ArgumentNullException.ThrowIfNull(parent); + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length"), nameof(name)); @@ -47,8 +50,11 @@ protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollecti /// null if the property couldn't be found. /// [RequiresUnreferencedCode("The Type of DesignerOptionCollection's value cannot be statically discovered.")] - private PropertyDescriptor? GetOptionProperty(string pageName!!, string valueName!!) + private PropertyDescriptor? GetOptionProperty(string pageName, string valueName) { + ArgumentNullException.ThrowIfNull(pageName); + ArgumentNullException.ThrowIfNull(valueName); + string[] optionNames = pageName.Split('\\'); DesignerOptionCollection? options = Options; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs index b22b655bf28922..001b781796b162 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerVerbCollection.cs @@ -21,16 +21,20 @@ public DesignerVerb? this[int index] public int Add(DesignerVerb? value) => List.Add(value); - public void AddRange(DesignerVerb?[] value!!) + public void AddRange(DesignerVerb?[] value) { + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(DesignerVerbCollection value!!) + public void AddRange(DesignerVerbCollection value) { + ArgumentNullException.ThrowIfNull(value); + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs index 1da32e75bb553e..e42bf8e0827f24 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs @@ -30,8 +30,10 @@ public class DesigntimeLicenseContext : LicenseContext /// /// Sets a saved license key. /// - public override void SetSavedLicenseKey(Type type!!, string key) + public override void SetSavedLicenseKey(Type type, string key) { + ArgumentNullException.ThrowIfNull(type); + _savedLicenseKeys[type.AssemblyQualifiedName!] = key; } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs index 1179fc405b1fbb..0381f5b21c3772 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/HelpKeywordAttribute.cs @@ -59,16 +59,20 @@ public HelpKeywordAttribute() /// /// Creates a HelpKeywordAttribute with the value being the given keyword string. /// - public HelpKeywordAttribute(string keyword!!) + public HelpKeywordAttribute(string keyword) { + ArgumentNullException.ThrowIfNull(keyword); + HelpKeyword = keyword; } /// /// Creates a HelpKeywordAttribute with the value being the full name of the given type. /// - public HelpKeywordAttribute(Type t!!) + public HelpKeywordAttribute(Type t) { + ArgumentNullException.ThrowIfNull(t); + HelpKeyword = t.FullName; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs index b0b88158fdcfb4..26f2d87b407c9b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/ContextStack.cs @@ -66,10 +66,12 @@ public object? this[int level] /// inherits from or implements the given type, or /// null if no object on the stack implements the type. /// - public object? this[Type type!!] + public object? this[Type type] { get { + ArgumentNullException.ThrowIfNull(type); + if (_contextStack != null) { int level = _contextStack.Count; @@ -94,8 +96,10 @@ public object? this[Type type!!] /// be popped in order. There is no way to remove an object that was /// appended to the end of the stack without popping all other objects. /// - public void Append(object context!!) + public void Append(object context) { + ArgumentNullException.ThrowIfNull(context); + if (_contextStack == null) { _contextStack = new List(); @@ -124,8 +128,10 @@ public void Append(object context!!) /// /// Pushes the given object onto the stack. /// - public void Push(object context!!) + public void Push(object context) { + ArgumentNullException.ThrowIfNull(context); + if (_contextStack == null) { _contextStack = new List(); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs index 060ad08d616df5..3931f161b1b281 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/DefaultSerializationProviderAttribute.cs @@ -16,16 +16,20 @@ public sealed class DefaultSerializationProviderAttribute : Attribute /// /// Creates a new DefaultSerializationProviderAttribute /// - public DefaultSerializationProviderAttribute(Type providerType!!) + public DefaultSerializationProviderAttribute(Type providerType) { + ArgumentNullException.ThrowIfNull(providerType); + ProviderTypeName = providerType.AssemblyQualifiedName!; } /// /// Creates a new DefaultSerializationProviderAttribute /// - public DefaultSerializationProviderAttribute(string providerTypeName!!) + public DefaultSerializationProviderAttribute(string providerTypeName) { + ArgumentNullException.ThrowIfNull(providerTypeName); + ProviderTypeName = providerTypeName; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index 54f7abcd9cfeb5..8f1d3adbc1282b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -69,14 +69,20 @@ public MemberRelationship this[MemberRelationship source] /// Also sets a relationship between two objects. Null can be passed as the property value, in which /// case the relationship will be cleared. /// - public MemberRelationship this[object sourceOwner!!, MemberDescriptor sourceMember!!] + public MemberRelationship this[object sourceOwner, MemberDescriptor sourceMember] { get { + ArgumentNullException.ThrowIfNull(sourceOwner); + ArgumentNullException.ThrowIfNull(sourceMember); + return GetRelationship(new MemberRelationship(sourceOwner, sourceMember)); } set { + ArgumentNullException.ThrowIfNull(sourceOwner); + ArgumentNullException.ThrowIfNull(sourceMember); + SetRelationship(new MemberRelationship(sourceOwner, sourceMember), value); } } @@ -179,8 +185,11 @@ public bool Equals(RelationshipEntry other) /// /// Creates a new member relationship. /// - public MemberRelationship(object owner!!, MemberDescriptor member!!) + public MemberRelationship(object owner, MemberDescriptor member) { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(member); + Owner = owner; Member = member; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs index 5063f826b00898..5af16c0dce5f4f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/RootDesignerSerializerAttribute.cs @@ -17,8 +17,11 @@ public sealed class RootDesignerSerializerAttribute : Attribute /// /// Creates a new designer serialization attribute. /// - public RootDesignerSerializerAttribute(Type serializerType!!, Type baseSerializerType!!, bool reloadable) + public RootDesignerSerializerAttribute(Type serializerType, Type baseSerializerType, bool reloadable) { + ArgumentNullException.ThrowIfNull(serializerType); + ArgumentNullException.ThrowIfNull(baseSerializerType); + SerializerTypeName = serializerType.AssemblyQualifiedName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; Reloadable = reloadable; @@ -27,8 +30,10 @@ public RootDesignerSerializerAttribute(Type serializerType!!, Type baseSerialize /// /// Creates a new designer serialization attribute. /// - public RootDesignerSerializerAttribute(string serializerTypeName, Type baseSerializerType!!, bool reloadable) + public RootDesignerSerializerAttribute(string serializerTypeName, Type baseSerializerType, bool reloadable) { + ArgumentNullException.ThrowIfNull(baseSerializerType); + SerializerTypeName = serializerTypeName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; Reloadable = reloadable; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs index 8f725c0ddb43be..81e10e504d83ed 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs @@ -115,8 +115,10 @@ private static long GetEnumValue(bool isUnderlyingTypeUInt64, Enum enumVal, Cult /// /// Converts the given value object to the specified destination type. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string) && value != null) { // Raise an argument exception if the value isn't defined and if diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs index 508c394d9a13f0..f9778163e1505f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs @@ -17,8 +17,10 @@ public class InstallerTypeAttribute : Attribute /// /// Initializes a new instance of the System.Windows.Forms.ComponentModel.InstallerTypeAttribute class. /// - public InstallerTypeAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type installerType!!) + public InstallerTypeAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type installerType) { + ArgumentNullException.ThrowIfNull(installerType); + _typeName = installerType.AssemblyQualifiedName; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs index 7fef5ef5ccaa7a..f210c54d5dede9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -882,8 +882,10 @@ public bool Add(string input) /// The MaskedTextResultHint out param gives a hint about the operation result reason. /// Returns true on success, false otherwise. /// - public bool Add(string input!!, out int testPosition, out MaskedTextResultHint resultHint) + public bool Add(string input, out int testPosition, out MaskedTextResultHint resultHint) { + ArgumentNullException.ThrowIfNull(input); + testPosition = LastAssignedPosition + 1; if (input.Length == 0) // nothing to add. @@ -1253,8 +1255,10 @@ public bool InsertAt(string input, int position) /// The MaskedTextResultHint out param gives more information about the operation result. /// Returns true on success, false otherwise. /// - public bool InsertAt(string input!!, int position, out int testPosition, out MaskedTextResultHint resultHint) + public bool InsertAt(string input, int position, out int testPosition, out MaskedTextResultHint resultHint) { + ArgumentNullException.ThrowIfNull(input); + if (position < 0 || position >= _testString.Length) { testPosition = position; @@ -1809,8 +1813,10 @@ public bool Replace(string input, int position) /// The MaskedTextResultHint out param gives more information about the operation result. /// Returns true on success, false otherwise. /// - public bool Replace(string input!!, int position, out int testPosition, out MaskedTextResultHint resultHint) + public bool Replace(string input, int position, out int testPosition, out MaskedTextResultHint resultHint) { + ArgumentNullException.ThrowIfNull(input); + if (position < 0 || position >= _testString.Length) { testPosition = position; @@ -1843,8 +1849,10 @@ public bool Replace(string input!!, int position, out int testPosition, out Mask /// The MaskedTextResultHint out param gives more information about the operation result. /// Returns true on success, false otherwise. /// - public bool Replace(string input!!, int startPosition, int endPosition, out int testPosition, out MaskedTextResultHint resultHint) + public bool Replace(string input, int startPosition, int endPosition, out int testPosition, out MaskedTextResultHint resultHint) { + ArgumentNullException.ThrowIfNull(input); + if (endPosition >= _testString.Length) { testPosition = endPosition; @@ -2024,8 +2032,10 @@ public bool Set(string input) /// The MaskedTextResultHint out param gives more information about the operation result. /// If passwordChar is assigned, it is rendered in the output string instead of the user-supplied values. /// - public bool Set(string input!!, out int testPosition, out MaskedTextResultHint resultHint) + public bool Set(string input, out int testPosition, out MaskedTextResultHint resultHint) { + ArgumentNullException.ThrowIfNull(input); + testPosition = 0; if (input.Length == 0) // Clearing the input text. diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs index 7bace2d4e7ecbe..e8b7e1fc9dd5f1 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs @@ -38,8 +38,10 @@ protected MemberDescriptor(string name) : this(name, null) /// /// Initializes a new instance of the class with the specified and array. /// - protected MemberDescriptor(string name!!, Attribute[]? attributes) + protected MemberDescriptor(string name, Attribute[]? attributes) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentException(SR.InvalidMemberName, nameof(name)); @@ -61,8 +63,10 @@ protected MemberDescriptor(string name!!, Attribute[]? attributes) /// /// Initializes a new instance of the class with the specified . /// - protected MemberDescriptor(MemberDescriptor descr!!) + protected MemberDescriptor(MemberDescriptor descr) { + ArgumentNullException.ThrowIfNull(descr); + _name = descr.Name; _displayName = _name; _nameHash = _name?.GetHashCode() ?? 0; @@ -80,8 +84,10 @@ protected MemberDescriptor(MemberDescriptor descr!!) /// and the attributes /// in both the old and the array. /// - protected MemberDescriptor(MemberDescriptor oldMemberDescriptor!!, Attribute[]? newAttributes) + protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[]? newAttributes) { + ArgumentNullException.ThrowIfNull(oldMemberDescriptor); + _name = oldMemberDescriptor.Name; _displayName = oldMemberDescriptor.DisplayName; _nameHash = _name.GetHashCode(); @@ -302,8 +308,10 @@ public override bool Equals([NotNullWhen(true)] object? obj) /// specified list of attributes in the parent class. For duplicate attributes, /// the last one added to the list will be kept. /// - protected virtual void FillAttributes(IList attributeList!!) + protected virtual void FillAttributes(IList attributeList) { + ArgumentNullException.ThrowIfNull(attributeList); + if (_originalAttributes != null) { foreach (Attribute attr in _originalAttributes) @@ -387,12 +395,14 @@ private void FilterAttributesIfNeeded() /// Finds the given method through reflection. /// protected static MethodInfo? FindMethod( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type componentClass!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type componentClass, string name, Type[] args, Type returnType, bool publicOnly) { + ArgumentNullException.ThrowIfNull(componentClass); + MethodInfo? result; if (publicOnly) { @@ -421,8 +431,11 @@ private void FilterAttributesIfNeeded() /// someone associated another object with this instance, or if the instance is a /// custom type descriptor, GetInvocationTarget may return a different value. /// - protected virtual object? GetInvocationTarget(Type type!!, object instance!!) + protected virtual object? GetInvocationTarget(Type type, object instance) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(instance); + return TypeDescriptor.GetAssociation(type, instance); } @@ -432,8 +445,11 @@ private void FilterAttributesIfNeeded() protected static ISite? GetSite(object? component) => (component as IComponent)?.Site; [Obsolete("MemberDescriptor.GetInvokee has been deprecated. Use GetInvocationTarget instead.")] - protected static object GetInvokee(Type componentClass!!, object component!!) + protected static object GetInvokee(Type componentClass, object component) { + ArgumentNullException.ThrowIfNull(componentClass); + ArgumentNullException.ThrowIfNull(component); + return TypeDescriptor.GetAssociation(componentClass, component); } } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs index 62275414eaa2ef..5a632e69e8600b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs @@ -14,8 +14,10 @@ public class MultilineStringConverter : TypeConverter /// /// Converts the given value object to the specified destination type. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string) && value is string) { return SR.Text; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs index d443705fc6d315..bd938f65d99be9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs @@ -18,8 +18,10 @@ public class NestedContainer : Container, INestedContainer /// /// Creates a new NestedContainer. /// - public NestedContainer(IComponent owner!!) + public NestedContainer(IComponent owner) { + ArgumentNullException.ThrowIfNull(owner); + Owner = owner; Owner.Disposed += new EventHandler(OnOwnerDisposed); } @@ -59,8 +61,10 @@ protected virtual string? OwnerName /// /// Creates a site for the component within the container. /// - protected override ISite CreateSite(IComponent component!!, string? name) + protected override ISite CreateSite(IComponent component, string? name) { + ArgumentNullException.ThrowIfNull(component); + return new Site(component, this, name); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs index ea8067fbd9fce9..f134b8ae8512a6 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs @@ -97,8 +97,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// /// Converts the given value object to the destination type. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == UnderlyingType && value != null && NullableType.IsInstanceOfType(value)) { return value; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs index 0300f9f3bbec8d..17611ac535888f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs @@ -122,8 +122,11 @@ public DesignerSerializationVisibility SerializationVisibility /// /// Allows interested objects to be notified when this property changes. /// - public virtual void AddValueChanged(object component!!, EventHandler handler!!) + public virtual void AddValueChanged(object component, EventHandler handler) { + ArgumentNullException.ThrowIfNull(component); + ArgumentNullException.ThrowIfNull(handler); + if (_valueChangedHandlers == null) { _valueChangedHandlers = new Dictionary(); @@ -391,8 +394,11 @@ protected virtual void OnValueChanged(object? component, EventArgs e) /// /// Allows interested objects to be notified when this property changes. /// - public virtual void RemoveValueChanged(object component!!, EventHandler handler!!) + public virtual void RemoveValueChanged(object component, EventHandler handler) { + ArgumentNullException.ThrowIfNull(component); + ArgumentNullException.ThrowIfNull(handler); + if (_valueChangedHandlers != null) { EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs index 639e76d3538317..d9663f14338b6c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs @@ -16,8 +16,10 @@ public sealed class ProvidePropertyAttribute : Attribute /// public ProvidePropertyAttribute( string propertyName, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type receiverType!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type receiverType) { + ArgumentNullException.ThrowIfNull(receiverType); + PropertyName = propertyName; ReceiverTypeName = receiverType.AssemblyQualifiedName!; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs index e5a11634c6e7bc..232709f9e5777a 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs @@ -481,8 +481,11 @@ private MethodInfo? ShouldSerializeMethodValue /// /// Allows interested objects to be notified when this property changes. /// - public override void AddValueChanged(object component!!, EventHandler handler!!) + public override void AddValueChanged(object component, EventHandler handler) { + ArgumentNullException.ThrowIfNull(component); + ArgumentNullException.ThrowIfNull(handler); + // If there's an event called Changed, hook the caller's handler directly up to that on the component EventDescriptor changedEvent = ChangedEventValue; if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index a92faf0c596ded..ad13f79f0221b0 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -227,8 +227,10 @@ internal static void ClearReflectionCaches() /// table for the editor type, if one can be found. /// [RequiresUnreferencedCode("The Types specified in table may be trimmed, or have their static construtors trimmed.")] - internal static void AddEditorTable(Type editorBaseType!!, Hashtable table) + internal static void AddEditorTable(Type editorBaseType, Hashtable table) { + ArgumentNullException.ThrowIfNull(editorBaseType); + Debug.Assert(table != null, "COMPAT: Editor table should not be null"); // don't throw; RTM didn't so we can't do it either. lock (s_internalSyncObject) @@ -618,8 +620,10 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) return properties; } - protected internal override IExtenderProvider[] GetExtenderProviders(object instance!!) + protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { + ArgumentNullException.ThrowIfNull(instance); + IComponent? component = instance as IComponent; if (component != null && component.Site != null) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs index d86d57cd0c198c..b6a2244400db68 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs @@ -46,16 +46,20 @@ public ToolboxItemAttribute(bool defaultType) /// /// Initializes a new instance of ToolboxItemAttribute and specifies the name of the type. /// - public ToolboxItemAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string toolboxItemTypeName!!) + public ToolboxItemAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string toolboxItemTypeName) { + ArgumentNullException.ThrowIfNull(toolboxItemTypeName); + _toolboxItemTypeName = toolboxItemTypeName; } /// /// Initializes a new instance of ToolboxItemAttribute and specifies the type of the toolbox item. /// - public ToolboxItemAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type toolboxItemType!!) + public ToolboxItemAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type toolboxItemType) { + ArgumentNullException.ThrowIfNull(toolboxItemType); + _toolboxItemType = toolboxItemType; _toolboxItemTypeName = toolboxItemType.AssemblyQualifiedName; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs index 5ce3f93ad0533b..e3ffc2fbd063a8 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs @@ -110,8 +110,10 @@ public virtual bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(t /// Converts the given value object to /// the specified destination type using the specified context and arguments. /// - public virtual object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public virtual object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string)) { if (value == null) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs index deb02e1689b910..df17a82d3e7fc9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs @@ -154,8 +154,10 @@ protected internal virtual IExtenderProvider[] GetExtenderProviders(object insta /// method will invoke the parent provider's GetReflectionType method. /// [RequiresUnreferencedCode("GetReflectionType is not trim compatible because the Type of object cannot be statically discovered.")] - public Type GetReflectionType(object instance!!) + public Type GetReflectionType(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return GetReflectionType(instance.GetType(), instance); } @@ -226,8 +228,10 @@ public virtual Type GetRuntimeType(Type reflectionType) /// return base. /// [RequiresUnreferencedCode("The Type of instance cannot be statically discovered.")] - public ICustomTypeDescriptor? GetTypeDescriptor(object instance!!) + public ICustomTypeDescriptor? GetTypeDescriptor(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return GetTypeDescriptor(instance.GetType(), instance); } @@ -259,8 +263,10 @@ public virtual Type GetRuntimeType(Type reflectionType) /// This method returns true if the type is "supported" by the type descriptor /// and its chain of type description providers. /// - public virtual bool IsSupportedType(Type type!!) + public virtual bool IsSupportedType(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (_parent != null) { return _parent.IsSupportedType(type); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs index 9fb2c5a8c34913..7edb2d85c94626 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -114,8 +114,11 @@ public static Type InterfaceType /// RemoveProvider if the added attributes are no longer needed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static TypeDescriptionProvider AddAttributes(Type type!!, params Attribute[] attributes!!) + public static TypeDescriptionProvider AddAttributes(Type type, params Attribute[] attributes) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(attributes); + TypeDescriptionProvider existingProvider = GetProvider(type); TypeDescriptionProvider provider = new AttributeProvider(existingProvider, attributes); TypeDescriptor.AddProvider(provider, type); @@ -133,8 +136,11 @@ public static TypeDescriptionProvider AddAttributes(Type type!!, params Attribut /// RemoveProvider if the added attributes are no longer needed. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static TypeDescriptionProvider AddAttributes(object instance!!, params Attribute[] attributes!!) + public static TypeDescriptionProvider AddAttributes(object instance, params Attribute[] attributes) { + ArgumentNullException.ThrowIfNull(instance); + ArgumentNullException.ThrowIfNull(attributes); + TypeDescriptionProvider existingProvider = GetProvider(instance); TypeDescriptionProvider provider = new AttributeProvider(existingProvider, attributes); AddProvider(provider, instance); @@ -164,8 +170,11 @@ public static void AddEditorTable(Type editorBaseType, Hashtable table) /// all types. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void AddProvider(TypeDescriptionProvider provider!!, Type type!!) + public static void AddProvider(TypeDescriptionProvider provider, Type type) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(type); + lock (s_providerTable) { // Get the root node, hook it up, and stuff it back into @@ -187,8 +196,11 @@ public static void AddProvider(TypeDescriptionProvider provider!!, Type type!!) /// the object from finalizing. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void AddProvider(TypeDescriptionProvider provider!!, object instance!!) + public static void AddProvider(TypeDescriptionProvider provider, object instance) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(instance); + bool refreshNeeded; // Get the root node, hook it up, and stuff it back into @@ -218,8 +230,11 @@ public static void AddProvider(TypeDescriptionProvider provider!!, object instan /// all types. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void AddProviderTransparent(TypeDescriptionProvider provider!!, Type type!!) + public static void AddProviderTransparent(TypeDescriptionProvider provider, Type type) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(type); + AddProvider(provider, type); } @@ -231,8 +246,11 @@ public static void AddProviderTransparent(TypeDescriptionProvider provider!!, Ty /// the object from finalizing. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void AddProviderTransparent(TypeDescriptionProvider provider!!, object instance!!) + public static void AddProviderTransparent(TypeDescriptionProvider provider, object instance) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(instance); + AddProvider(provider, instance); } @@ -301,8 +319,11 @@ private static void CheckDefaultProvider(Type type) /// instance that is related to its type parameter. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void CreateAssociation(object primary!!, object secondary!!) + public static void CreateAssociation(object primary, object secondary) { + ArgumentNullException.ThrowIfNull(primary); + ArgumentNullException.ThrowIfNull(secondary); + if (primary == secondary) { throw new ArgumentException(SR.TypeDescriptorSameAssociation); @@ -372,10 +393,12 @@ public static EventDescriptor CreateEvent( /// public static object? CreateInstance( IServiceProvider? provider, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType, Type[]? argTypes, object[]? args) { + ArgumentNullException.ThrowIfNull(objectType); + if (argTypes != null) { ArgumentNullException.ThrowIfNull(args); @@ -498,8 +521,11 @@ public static PropertyDescriptor CreateProperty( /// for the requested type. It never returns null. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static object GetAssociation(Type type!!, object primary!!) + public static object GetAssociation(Type type, object primary) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(primary); + object associatedObject = primary; if (!type.IsInstanceOfType(primary)) @@ -837,9 +863,11 @@ internal static TypeConverter GetConverterTrimUnsafe([DynamicallyAccessedMembers /// Performs arg checking so callers don't have to. /// internal static ICustomTypeDescriptor? GetDescriptor( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string typeName) { + ArgumentNullException.ThrowIfNull(type); + return NodeFor(type).GetTypeDescriptor(type); } @@ -897,8 +925,10 @@ internal static ICustomTypeDescriptor GetExtendedDescriptor(object component) /// [EditorBrowsable(EditorBrowsableState.Advanced)] [RequiresUnreferencedCode(EditorRequiresUnreferencedCode + " The Type of component cannot be statically discovered.")] - public static object? GetEditor(object component, Type editorBaseType!!, bool noCustomTypeDesc) + public static object? GetEditor(object component, Type editorBaseType, bool noCustomTypeDesc) { + ArgumentNullException.ThrowIfNull(editorBaseType); + return GetDescriptor(component, noCustomTypeDesc)!.GetEditor(editorBaseType); } @@ -908,8 +938,10 @@ internal static ICustomTypeDescriptor GetExtendedDescriptor(object component) [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] public static object? GetEditor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, - Type editorBaseType!!) + Type editorBaseType) { + ArgumentNullException.ThrowIfNull(editorBaseType); + return GetDescriptor(type, nameof(type))!.GetEditor(editorBaseType); } @@ -1120,8 +1152,10 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[]? /// return a different fully qualified name. /// [RequiresUnreferencedCode("The Type of component cannot be statically discovered.")] - public static string? GetFullComponentName(object component!!) + public static string? GetFullComponentName(object component) { + ArgumentNullException.ThrowIfNull(component); + return GetProvider(component).GetFullComponentName(component); } @@ -1323,8 +1357,10 @@ private static PropertyDescriptorCollection GetPropertiesImpl(object component, /// another provider that someone else has added. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static TypeDescriptionProvider GetProvider(Type type!!) + public static TypeDescriptionProvider GetProvider(Type type) { + ArgumentNullException.ThrowIfNull(type); + return NodeFor(type, true); } @@ -1336,8 +1372,10 @@ public static TypeDescriptionProvider GetProvider(Type type!!) /// another provider that someone else has added. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static TypeDescriptionProvider GetProvider(object instance!!) + public static TypeDescriptionProvider GetProvider(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return NodeFor(instance, true); } @@ -1358,8 +1396,10 @@ internal static TypeDescriptionProvider GetProviderRecursive(Type type) /// [EditorBrowsable(EditorBrowsableState.Advanced)] [return: DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] - public static Type GetReflectionType([DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] Type type!!) + public static Type GetReflectionType([DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] Type type) { + ArgumentNullException.ThrowIfNull(type); + return NodeFor(type).GetReflectionType(type); } @@ -1368,8 +1408,10 @@ public static Type GetReflectionType([DynamicallyAccessedMembers(ReflectTypesDyn /// [EditorBrowsable(EditorBrowsableState.Advanced)] [RequiresUnreferencedCode("GetReflectionType is not trim compatible because the Type of object cannot be statically discovered.")] - public static Type GetReflectionType(object instance!!) + public static Type GetReflectionType(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return NodeFor(instance).GetReflectionType(instance); } @@ -2352,8 +2394,11 @@ public static IComNativeDescriptorHandler? ComNativeDescriptorHandler /// The RemoveAssociation method removes an association with an object. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveAssociation(object primary!!, object secondary!!) + public static void RemoveAssociation(object primary, object secondary) { + ArgumentNullException.ThrowIfNull(primary); + ArgumentNullException.ThrowIfNull(secondary); + Hashtable assocTable = AssociationTable; IList? associations = (IList?)assocTable?[primary]; if (associations != null) @@ -2379,8 +2424,10 @@ public static void RemoveAssociation(object primary!!, object secondary!!) /// The RemoveAssociations method removes all associations for a primary object. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveAssociations(object primary!!) + public static void RemoveAssociations(object primary) { + ArgumentNullException.ThrowIfNull(primary); + Hashtable assocTable = AssociationTable; assocTable?.Remove(primary); } @@ -2392,8 +2439,11 @@ public static void RemoveAssociations(object primary!!) /// associated with. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveProvider(TypeDescriptionProvider provider!!, Type type!!) + public static void RemoveProvider(TypeDescriptionProvider provider, Type type) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(type); + // Walk the nodes until we find the right one, and then remove it. NodeRemove(type, provider); RaiseRefresh(type); @@ -2406,8 +2456,11 @@ public static void RemoveProvider(TypeDescriptionProvider provider!!, Type type! /// associated with. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveProvider(TypeDescriptionProvider provider!!, object instance!!) + public static void RemoveProvider(TypeDescriptionProvider provider, object instance) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(instance); + // Walk the nodes until we find the right one, and then remove it. NodeRemove(instance, provider); RaiseRefresh(instance); @@ -2421,8 +2474,11 @@ public static void RemoveProvider(TypeDescriptionProvider provider!!, object ins /// associated with. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveProviderTransparent(TypeDescriptionProvider provider!!, Type type!!) + public static void RemoveProviderTransparent(TypeDescriptionProvider provider, Type type) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(type); + RemoveProvider(provider, type); } @@ -2433,8 +2489,11 @@ public static void RemoveProviderTransparent(TypeDescriptionProvider provider!!, /// associated with. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveProviderTransparent(TypeDescriptionProvider provider!!, object instance!!) + public static void RemoveProviderTransparent(TypeDescriptionProvider provider, object instance) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(instance); + RemoveProvider(provider, instance); } @@ -2466,8 +2525,10 @@ private static bool ShouldHideMember(MemberDescriptor? member, Attribute? attrib /// /// Sorts descriptors by name of the descriptor. /// - public static void SortDescriptorArray(IList infos!!) + public static void SortDescriptorArray(IList infos) { + ArgumentNullException.ThrowIfNull(infos); + ArrayList.Adapter(infos).Sort(MemberDescriptorComparer.Instance); } @@ -2494,8 +2555,10 @@ internal ComNativeDescriptionProvider(IComNativeDescriptorHandler handler) /// descriptor that walks the linked list for each of its calls. /// [return: NotNullIfNotNull("instance")] - public override ICustomTypeDescriptor? GetTypeDescriptor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type objectType!!, object? instance) + public override ICustomTypeDescriptor? GetTypeDescriptor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type objectType, object? instance) { + ArgumentNullException.ThrowIfNull(objectType); + if (instance == null) { return null; @@ -2863,8 +2926,10 @@ TypeConverter ICustomTypeDescriptor.GetConverter() /// ICustomTypeDescriptor implementation. /// [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType!!) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) { + ArgumentNullException.ThrowIfNull(editorBaseType); + object? editor = _primary.GetEditor(editorBaseType) ?? _secondary.GetEditor(editorBaseType); return editor; @@ -2958,10 +3023,12 @@ internal TypeDescriptionNode(TypeDescriptionProvider provider) /// public override object? CreateInstance( IServiceProvider? provider, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType, Type[]? argTypes, object[]? args) { + ArgumentNullException.ThrowIfNull(objectType); + if (argTypes != null) { ArgumentNullException.ThrowIfNull(args); @@ -2979,8 +3046,10 @@ internal TypeDescriptionNode(TypeDescriptionProvider provider) /// Implements GetCache. This just walks the linked /// list looking for someone who implements the call. /// - public override IDictionary? GetCache(object instance!!) + public override IDictionary? GetCache(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return Provider.GetCache(instance); } @@ -2989,13 +3058,17 @@ internal TypeDescriptionNode(TypeDescriptionProvider provider) /// descriptor that walks the linked list for each of its calls. /// [RequiresUnreferencedCode("The Type of instance cannot be statically discovered.")] - public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance!!) + public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return new DefaultExtendedTypeDescriptor(this, instance); } - protected internal override IExtenderProvider[] GetExtenderProviders(object instance!!) + protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { + ArgumentNullException.ThrowIfNull(instance); + return Provider.GetExtenderProviders(instance); } @@ -3009,8 +3082,10 @@ protected internal override IExtenderProvider[] GetExtenderProviders(object inst /// GetTypeDescriptor.GetComponentName. /// [RequiresUnreferencedCode("The Type of component cannot be statically discovered.")] - public override string? GetFullComponentName(object component!!) + public override string? GetFullComponentName(object component) { + ArgumentNullException.ThrowIfNull(component); + return Provider.GetFullComponentName(component); } @@ -3020,14 +3095,18 @@ protected internal override IExtenderProvider[] GetExtenderProviders(object inst /// [return: DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] public override Type GetReflectionType( - [DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] Type objectType!!, + [DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] Type objectType, object? instance) { + ArgumentNullException.ThrowIfNull(objectType); + return Provider.GetReflectionType(objectType, instance); } - public override Type GetRuntimeType(Type objectType!!) + public override Type GetRuntimeType(Type objectType) { + ArgumentNullException.ThrowIfNull(objectType); + return Provider.GetRuntimeType(objectType); } @@ -3035,8 +3114,10 @@ public override Type GetRuntimeType(Type objectType!!) /// Implements GetTypeDescriptor. This creates a custom type /// descriptor that walks the linked list for each of its calls. /// - public override ICustomTypeDescriptor GetTypeDescriptor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type objectType!!, object? instance) + public override ICustomTypeDescriptor GetTypeDescriptor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type objectType, object? instance) { + ArgumentNullException.ThrowIfNull(objectType); + if (instance != null && !objectType.IsInstanceOfType(instance)) { throw new ArgumentException(nameof(instance)); @@ -3045,8 +3126,10 @@ public override ICustomTypeDescriptor GetTypeDescriptor([DynamicallyAccessedMemb return new DefaultTypeDescriptor(this, objectType, instance); } - public override bool IsSupportedType(Type type!!) + public override bool IsSupportedType(Type type) { + ArgumentNullException.ThrowIfNull(type); + return Provider.IsSupportedType(type); } @@ -3203,8 +3286,10 @@ TypeConverter ICustomTypeDescriptor.GetConverter() /// ICustomTypeDescriptor implementation. /// [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType!!) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) { + ArgumentNullException.ThrowIfNull(editorBaseType); + // Check to see if the provider we get is a ReflectTypeDescriptionProvider. // If so, we can call on it directly rather than creating another // custom type descriptor @@ -3525,8 +3610,10 @@ TypeConverter ICustomTypeDescriptor.GetConverter() /// ICustomTypeDescriptor implementation. /// [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType!!) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) { + ArgumentNullException.ThrowIfNull(editorBaseType); + // Check to see if the provider we get is a ReflectTypeDescriptionProvider. // If so, we can call on it directly rather than creating another // custom type descriptor diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs index 5f5948700d4004..154cca5ae7c6be 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs @@ -65,8 +65,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// /// Converts the given value object to the specified destination type. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string)) { if (value == null) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs index 546991ed7c4fe7..6cff19cdfe4ae0 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs @@ -62,8 +62,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// Converts the given value object to /// the specified destination type using the specified context and arguments. /// - public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is Uri uri) { if (destinationType == typeof(InstanceDescriptor)) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs index 729321fe96b623..0d7bf0e2b672df 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs @@ -63,8 +63,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// Converts the given value object to /// the specified destination type using the specified context and arguments. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is Version version) { if (destinationType == typeof(InstanceDescriptor)) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs index 5a317f1401b54f..9a6117b17c6450 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs @@ -45,8 +45,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertFrom(context, culture, value); } - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is Color c) { if (destinationType == typeof(string)) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs index 7df91fd7a3148c..0eee25d7ac7f96 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs @@ -61,8 +61,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertFrom(context, culture, value); } - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is Point pt) { if (destinationType == typeof(string)) @@ -96,8 +98,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) { + ArgumentNullException.ThrowIfNull(propertyValues); + object? x = propertyValues["X"]; object? y = propertyValues["Y"]; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs index 21a881bf17f392..93d6ae1c5181f3 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs @@ -59,8 +59,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertFrom(context, culture, value); } - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is Rectangle rect) { if (destinationType == typeof(string)) @@ -99,8 +101,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) { + ArgumentNullException.ThrowIfNull(propertyValues); + object? x = propertyValues["X"]; object? y = propertyValues["Y"]; object? width = propertyValues["Width"]; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs index c224b31090d724..6bb0d1087e8d91 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs @@ -59,8 +59,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertFrom(context, culture, value); } - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is Size size) { if (destinationType == typeof(string)) @@ -94,8 +96,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) { + ArgumentNullException.ThrowIfNull(propertyValues); + object? width = propertyValues["Width"]; object? height = propertyValues["Height"]; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs index f166991f5d07b0..3e3cdb35353f73 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs @@ -58,8 +58,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertFrom(context, culture, value); } - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (value is SizeF size) { if (destinationType == typeof(string)) @@ -91,8 +93,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) { + ArgumentNullException.ThrowIfNull(propertyValues); + object? width = propertyValues["Width"]; object? height = propertyValues["Height"]; diff --git a/src/libraries/System.Composition.AttributedModel/src/System/Composition/PartMetadataAttribute.cs b/src/libraries/System.Composition.AttributedModel/src/System/Composition/PartMetadataAttribute.cs index 70c45e8aff1bcd..5564909ab1b90e 100644 --- a/src/libraries/System.Composition.AttributedModel/src/System/Composition/PartMetadataAttribute.cs +++ b/src/libraries/System.Composition.AttributedModel/src/System/Composition/PartMetadataAttribute.cs @@ -21,9 +21,9 @@ public class PartMetadataAttribute : Attribute /// An containing the metadata value. This can be /// . /// - public PartMetadataAttribute(string name!!, object value) + public PartMetadataAttribute(string name, object value) { - Name = name; + Name = name ?? throw new ArgumentNullException(nameof(name)); Value = value; } diff --git a/src/libraries/System.Composition.AttributedModel/src/System/Composition/SharingBoundaryAttribute.cs b/src/libraries/System.Composition.AttributedModel/src/System/Composition/SharingBoundaryAttribute.cs index 2ab60b99bbb8be..e3f93414c4fa42 100644 --- a/src/libraries/System.Composition.AttributedModel/src/System/Composition/SharingBoundaryAttribute.cs +++ b/src/libraries/System.Composition.AttributedModel/src/System/Composition/SharingBoundaryAttribute.cs @@ -27,9 +27,9 @@ public sealed class SharingBoundaryAttribute : Attribute /// Construct a for the specified boundary names. /// /// Boundaries implemented by the created ExportLifetimeContext{T}s. - public SharingBoundaryAttribute(params string[] sharingBoundaryNames!!) + public SharingBoundaryAttribute(params string[] sharingBoundaryNames) { - _sharingBoundaryNames = sharingBoundaryNames; + _sharingBoundaryNames = sharingBoundaryNames ?? throw new ArgumentNullException(nameof(sharingBoundaryNames)); } /// diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs index c1185c2413b2d1..7db2e4050def9d 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ConventionBuilder.cs @@ -45,8 +45,13 @@ public PartConventionBuilder ForTypesDerivedFrom() /// /// The type from which matching types derive. /// A that must be used to specify the rule. - public PartConventionBuilder ForTypesDerivedFrom(Type type!!) + public PartConventionBuilder ForTypesDerivedFrom(Type type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + var partBuilder = new PartConventionBuilder((t) => IsDescendentOf(t, type)); _conventions.Add(partBuilder); return partBuilder; @@ -69,8 +74,13 @@ public PartConventionBuilder ForType() /// /// The type to which the rule applies. /// A that must be used to specify the rule. - public PartConventionBuilder ForType(Type type!!) + public PartConventionBuilder ForType(Type type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + var partBuilder = new PartConventionBuilder((t) => t == type); _conventions.Add(partBuilder); return partBuilder; @@ -83,8 +93,13 @@ public PartConventionBuilder ForType(Type type!!) /// A predicate that selects matching types. /// The type to which the rule applies. /// A that must be used to specify the rule. - public PartConventionBuilder ForTypesMatching(Predicate typeFilter!!) + public PartConventionBuilder ForTypesMatching(Predicate typeFilter) { + if (typeFilter is null) + { + throw new ArgumentNullException(nameof(typeFilter)); + } + var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; @@ -96,8 +111,13 @@ public PartConventionBuilder ForTypesMatching(Predicate typeFilter!! /// /// A predicate that selects matching types. /// A that must be used to specify the rule. - public PartConventionBuilder ForTypesMatching(Predicate typeFilter!!) + public PartConventionBuilder ForTypesMatching(Predicate typeFilter) { + if (typeFilter is null) + { + throw new ArgumentNullException(nameof(typeFilter)); + } + var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; @@ -136,8 +156,13 @@ private IEnumerable>> EvaluateThisTypeInfoAgainstT /// The reflectedType the type used to retrieve the memberInfo. /// The member to supply attributes for. /// The list of applied attributes. - public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member!!) + public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member) { + if (member is null) + { + throw new ArgumentNullException(nameof(member)); + } + // Now edit the attributes returned from the base type List cachedAttributes = null; var typeInfo = member as TypeInfo; @@ -271,8 +296,13 @@ private List ReadMemberCustomAttributes(Type reflectedType, System.Re /// The reflectedType the type used to retrieve the parameterInfo. /// The parameter to supply attributes for. /// The list of applied attributes. - public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter!!) + public override IEnumerable GetCustomAttributes(Type reflectedType, System.Reflection.ParameterInfo parameter) { + if (parameter is null) + { + throw new ArgumentNullException(nameof(parameter)); + } + IEnumerable attributes = parameter.GetCustomAttributes(false); List cachedAttributes = ReadParameterCustomAttributes(reflectedType, parameter); return cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes); diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs index a0bcdf7fe06a05..abd5238e421caf 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ExportConventionBuilder.cs @@ -38,8 +38,13 @@ public ExportConventionBuilder AsContractType() /// /// The contract type. /// An export builder allowing further configuration. - public ExportConventionBuilder AsContractType(Type type!!) + public ExportConventionBuilder AsContractType(Type type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + _contractType = type; return this; } @@ -49,8 +54,13 @@ public ExportConventionBuilder AsContractType(Type type!!) /// /// The contract name. /// An export builder allowing further configuration. - public ExportConventionBuilder AsContractName(string contractName!!) + public ExportConventionBuilder AsContractName(string contractName) { + if (contractName is null) + { + throw new ArgumentNullException(nameof(contractName)); + } + if (contractName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(contractName)), nameof(contractName)); @@ -64,8 +74,13 @@ public ExportConventionBuilder AsContractName(string contractName!!) /// /// A Func to retrieve the contract name from the part typeThe contract name. /// An export builder allowing further configuration. - public ExportConventionBuilder AsContractName(Func getContractNameFromPartType!!) + public ExportConventionBuilder AsContractName(Func getContractNameFromPartType) { + if (getContractNameFromPartType is null) + { + throw new ArgumentNullException(nameof(getContractNameFromPartType)); + } + _getContractNameFromPartType = getContractNameFromPartType; return this; } @@ -76,8 +91,13 @@ public ExportConventionBuilder AsContractName(Func getContractName /// The name of the metadata item. /// The value of the metadata item. /// An export builder allowing further configuration. - public ExportConventionBuilder AddMetadata(string name!!, object value) + public ExportConventionBuilder AddMetadata(string name, object value) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); @@ -96,8 +116,17 @@ public ExportConventionBuilder AddMetadata(string name!!, object value) /// The name of the metadata item. /// A function that calculates the metadata value based on the type. /// An export builder allowing further configuration. - public ExportConventionBuilder AddMetadata(string name!!, Func getValueFromPartType!!) + public ExportConventionBuilder AddMetadata(string name, Func getValueFromPartType) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (getValueFromPartType is null) + { + throw new ArgumentNullException(nameof(getValueFromPartType)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs index 6be7f59b7ae8bd..804d9e5713f8d7 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs @@ -28,8 +28,13 @@ internal ImportConventionBuilder() { } /// /// /// An import builder allowing further configuration. - public ImportConventionBuilder AsContractName(string contractName!!) + public ImportConventionBuilder AsContractName(string contractName) { + if (contractName is null) + { + throw new ArgumentNullException(nameof(contractName)); + } + if (contractName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(contractName)), nameof(contractName)); @@ -43,8 +48,13 @@ public ImportConventionBuilder AsContractName(string contractName!!) /// /// A Func to retrieve the contract name from the part typeThe contract name. /// An export builder allowing further configuration. - public ImportConventionBuilder AsContractName(Func getContractNameFromPartType!!) + public ImportConventionBuilder AsContractName(Func getContractNameFromPartType) { + if (getContractNameFromPartType is null) + { + throw new ArgumentNullException(nameof(getContractNameFromPartType)); + } + _getContractNameFromPartType = getContractNameFromPartType; return this; } @@ -86,8 +96,13 @@ public ImportConventionBuilder AllowDefault() /// The name of the constraint item. /// The value to match. /// An import builder allowing further configuration. - public ImportConventionBuilder AddMetadataConstraint(string name!!, object value) + public ImportConventionBuilder AddMetadataConstraint(string name, object value) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); @@ -106,8 +121,17 @@ public ImportConventionBuilder AddMetadataConstraint(string name!!, object value /// The name of the constraint item. /// A function that calculates the value to match. /// An export builder allowing further configuration. - public ImportConventionBuilder AddMetadataConstraint(string name!!, Func getConstraintValueFromPartType!!) + public ImportConventionBuilder AddMetadataConstraint(string name, Func getConstraintValueFromPartType) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (getConstraintValueFromPartType is null) + { + throw new ArgumentNullException(nameof(getConstraintValueFromPartType)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs index 178cd730b07726..cd30e94212e789 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilder.cs @@ -63,8 +63,13 @@ public PartConventionBuilder Export() /// /// Configuration action for the export. /// A part builder allowing further configuration of the part. - public PartConventionBuilder Export(Action exportConfiguration!!) + public PartConventionBuilder Export(Action exportConfiguration) { + if (exportConfiguration is null) + { + throw new ArgumentNullException(nameof(exportConfiguration)); + } + var exportBuilder = new ExportConventionBuilder(); exportConfiguration(exportBuilder); _typeExportBuilders.Add(exportBuilder); @@ -87,8 +92,13 @@ public PartConventionBuilder Export() /// /// Configuration action for the export. /// A part builder allowing further configuration of the part. - public PartConventionBuilder Export(Action exportConfiguration!!) + public PartConventionBuilder Export(Action exportConfiguration) { + if (exportConfiguration is null) + { + throw new ArgumentNullException(nameof(exportConfiguration)); + } + ExportConventionBuilder exportBuilder = new ExportConventionBuilder().AsContractType(); exportConfiguration(exportBuilder); _typeExportBuilders.Add(exportBuilder); @@ -100,8 +110,13 @@ public PartConventionBuilder Export(Action exportCon /// /// Filter that selects a single constructor. /// A part builder allowing further configuration of the part. - public PartConventionBuilder SelectConstructor(Func, ConstructorInfo> constructorSelector!!) + public PartConventionBuilder SelectConstructor(Func, ConstructorInfo> constructorSelector) { + if (constructorSelector is null) + { + throw new ArgumentNullException(nameof(constructorSelector)); + } + _constructorFilter = constructorSelector; return this; } @@ -113,8 +128,13 @@ public PartConventionBuilder SelectConstructor(Func /// Action configuring the parameters of the selected constructor. /// A part builder allowing further configuration of the part. public PartConventionBuilder SelectConstructor(Func, ConstructorInfo> constructorSelector, - Action importConfiguration!!) + Action importConfiguration) { + if (importConfiguration is null) + { + throw new ArgumentNullException(nameof(importConfiguration)); + } + _configureConstuctorImports = importConfiguration; SelectConstructor(constructorSelector); return this; @@ -125,8 +145,13 @@ public PartConventionBuilder SelectConstructor(Func /// /// Filter for interfaces. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter!!) + public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter) { + if (interfaceFilter is null) + { + throw new ArgumentNullException(nameof(interfaceFilter)); + } + return ExportInterfacesImpl(interfaceFilter, null); } @@ -145,9 +170,18 @@ public PartConventionBuilder ExportInterfaces() /// Filter for interfaces. /// Action to configure selected interfaces. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter!!, - Action exportConfiguration!!) + public PartConventionBuilder ExportInterfaces(Predicate interfaceFilter, + Action exportConfiguration) { + if (interfaceFilter is null) + { + throw new ArgumentNullException(nameof(interfaceFilter)); + } + if (exportConfiguration is null) + { + throw new ArgumentNullException(nameof(exportConfiguration)); + } + return ExportInterfacesImpl(interfaceFilter, exportConfiguration); } @@ -163,8 +197,13 @@ private PartConventionBuilder ExportInterfacesImpl(Predicate interfaceFilt /// /// Selector for exported properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ExportProperties(Predicate propertyFilter!!) + public PartConventionBuilder ExportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ExportPropertiesImpl(propertyFilter, null); } @@ -174,9 +213,18 @@ public PartConventionBuilder ExportProperties(Predicate propertyFi /// Selector for exported properties. /// Action to configure selected properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ExportProperties(Predicate propertyFilter!!, - Action exportConfiguration!!) + public PartConventionBuilder ExportProperties(Predicate propertyFilter, + Action exportConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + if (exportConfiguration is null) + { + throw new ArgumentNullException(nameof(exportConfiguration)); + } + return ExportPropertiesImpl(propertyFilter, exportConfiguration); } @@ -193,8 +241,13 @@ private PartConventionBuilder ExportPropertiesImpl(Predicate prope /// Contract type to export. /// Filter to select matching properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ExportProperties(Predicate propertyFilter!!) + public PartConventionBuilder ExportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ExportPropertiesImpl(propertyFilter, null); } @@ -205,9 +258,18 @@ public PartConventionBuilder ExportProperties(Predicate propert /// Filter to select matching properties. /// Action to configure selected properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ExportProperties(Predicate propertyFilter!!, - Action exportConfiguration!!) + public PartConventionBuilder ExportProperties(Predicate propertyFilter, + Action exportConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + if (exportConfiguration is null) + { + throw new ArgumentNullException(nameof(exportConfiguration)); + } + return ExportPropertiesImpl(propertyFilter, exportConfiguration); } @@ -223,8 +285,13 @@ private PartConventionBuilder ExportPropertiesImpl(Predicate pr /// /// Filter to select matching properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ImportProperties(Predicate propertyFilter!!) + public PartConventionBuilder ImportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ImportPropertiesImpl(propertyFilter, null); } @@ -234,9 +301,18 @@ public PartConventionBuilder ImportProperties(Predicate propertyFi /// Filter to select matching properties. /// Action to configure selected properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ImportProperties(Predicate propertyFilter!!, - Action importConfiguration!!) + public PartConventionBuilder ImportProperties(Predicate propertyFilter, + Action importConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + if (importConfiguration is null) + { + throw new ArgumentNullException(nameof(importConfiguration)); + } + return ImportPropertiesImpl(propertyFilter, importConfiguration); } @@ -253,8 +329,13 @@ private PartConventionBuilder ImportPropertiesImpl(Predicate prope /// Property type to import. /// Filter to select matching properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ImportProperties(Predicate propertyFilter!!) + public PartConventionBuilder ImportProperties(Predicate propertyFilter) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + return ImportPropertiesImpl(propertyFilter, null); } @@ -265,9 +346,18 @@ public PartConventionBuilder ImportProperties(Predicate propert /// Filter to select matching properties. /// Action to configure selected properties. /// A part builder allowing further configuration of the part. - public PartConventionBuilder ImportProperties(Predicate propertyFilter!!, - Action importConfiguration!!) + public PartConventionBuilder ImportProperties(Predicate propertyFilter, + Action importConfiguration) { + if (propertyFilter is null) + { + throw new ArgumentNullException(nameof(propertyFilter)); + } + if (importConfiguration is null) + { + throw new ArgumentNullException(nameof(importConfiguration)); + } + return ImportPropertiesImpl(propertyFilter, importConfiguration); } @@ -303,8 +393,13 @@ public PartConventionBuilder Shared() /// /// Name of the sharing boundary. /// A part builder allowing further configuration of the part. - public PartConventionBuilder Shared(string sharingBoundary!!) + public PartConventionBuilder Shared(string sharingBoundary) { + if (sharingBoundary is null) + { + throw new ArgumentNullException(nameof(sharingBoundary)); + } + if (sharingBoundary.Length == 0) { throw new ArgumentException(SR.ArgumentException_EmptyString); @@ -326,8 +421,13 @@ private PartConventionBuilder SharedImpl(string sharingBoundary) /// The metadata name. /// The metadata value. /// A part builder allowing further configuration of the part. - public PartConventionBuilder AddPartMetadata(string name!!, object value) + public PartConventionBuilder AddPartMetadata(string name, object value) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); @@ -347,8 +447,17 @@ public PartConventionBuilder AddPartMetadata(string name!!, object value) /// The metadata name. /// A function mapping the part type to the metadata value. /// A part builder allowing further configuration of the part. - public PartConventionBuilder AddPartMetadata(string name!!, Func getValueFromPartType!!) + public PartConventionBuilder AddPartMetadata(string name, Func getValueFromPartType) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (getValueFromPartType is null) + { + throw new ArgumentNullException(nameof(getValueFromPartType)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs index 0dd3993734a21e..b60eb8aa07015e 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs @@ -27,8 +27,13 @@ public bool VerifyMethodInfo(MethodInfo mi) return mi == _methodInfo; } - private static MethodInfo SelectMethods(Expression> methodSelector!!) + private static MethodInfo SelectMethods(Expression> methodSelector) { + if (methodSelector is null) + { + throw new ArgumentNullException(nameof(methodSelector)); + } + Expression expr = Reduce(methodSelector).Body; if (expr.NodeType == ExpressionType.Call) { @@ -93,8 +98,13 @@ public void ConfigureExport(PropertyInfo propertyInfo, ExportConventionBuilder e _configureExport?.Invoke(exportBuilder); } - private static PropertyInfo SelectProperties(Expression> propertySelector!!) + private static PropertyInfo SelectProperties(Expression> propertySelector) { + if (propertySelector is null) + { + throw new ArgumentNullException(nameof(propertySelector)); + } + Expression expr = Reduce(propertySelector).Body; if (expr.NodeType == ExpressionType.MemberAccess) { @@ -147,8 +157,13 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConve return; } - private void ParseSelectConstructor(Expression> constructorSelector!!) + private void ParseSelectConstructor(Expression> constructorSelector) { + if (constructorSelector is null) + { + throw new ArgumentNullException(nameof(constructorSelector)); + } + Expression expr = Reduce(constructorSelector).Body; if (expr.NodeType != ExpressionType.New) { @@ -203,8 +218,13 @@ internal PartConventionBuilder(Predicate selectType) : base(selectType) /// /// Expression that selects a single constructor. /// A part builder allowing further configuration of the part. - public PartConventionBuilder SelectConstructor(Expression> constructorSelector!!) + public PartConventionBuilder SelectConstructor(Expression> constructorSelector) { + if (constructorSelector is null) + { + throw new ArgumentNullException(nameof(constructorSelector)); + } + var adapter = new ConstructorExpressionAdapter(constructorSelector); base.SelectConstructor(adapter.SelectConstructor, adapter.ConfigureConstructorImports); return this; @@ -227,9 +247,14 @@ public PartConventionBuilder ExportProperty(Expression> prope /// Action to configure selected properties. /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportProperty( - Expression> propertySelector!!, + Expression> propertySelector, Action exportConfiguration) { + if (propertySelector is null) + { + throw new ArgumentNullException(nameof(propertySelector)); + } + var adapter = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); base.ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); return this; @@ -255,9 +280,14 @@ public PartConventionBuilder ExportProperty(ExpressionAction to configure selected properties. /// A part builder allowing further configuration of the part. public PartConventionBuilder ExportProperty( - Expression> propertySelector!!, + Expression> propertySelector, Action exportConfiguration) { + if (propertySelector is null) + { + throw new ArgumentNullException(nameof(propertySelector)); + } + var adapter = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); base.ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); return this; @@ -280,9 +310,14 @@ public PartConventionBuilder ImportProperty(Expression> prope /// Action configuring the imported property. /// A part builder allowing further configuration of the part. public PartConventionBuilder ImportProperty( - Expression> propertySelector!!, + Expression> propertySelector, Action importConfiguration) { + if (propertySelector is null) + { + throw new ArgumentNullException(nameof(propertySelector)); + } + var adapter = new PropertyExpressionAdapter(propertySelector, importConfiguration, null); base.ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); return this; @@ -307,9 +342,14 @@ public PartConventionBuilder ImportProperty(ExpressionAction configuring the imported property. /// A part builder allowing further configuration of the part. public PartConventionBuilder ImportProperty( - Expression> propertySelector!!, + Expression> propertySelector, Action importConfiguration) { + if (propertySelector is null) + { + throw new ArgumentNullException(nameof(propertySelector)); + } + var adapter = new PropertyExpressionAdapter(propertySelector, importConfiguration, null); base.ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); return this; @@ -319,8 +359,13 @@ public PartConventionBuilder ImportProperty( /// Mark the part as being shared within the entire composition. /// /// A part builder allowing further configuration of the part. - public PartConventionBuilder NotifyImportsSatisfied(Expression> methodSelector!!) + public PartConventionBuilder NotifyImportsSatisfied(Expression> methodSelector) { + if (methodSelector is null) + { + throw new ArgumentNullException(nameof(methodSelector)); + } + var adapter = new MethodExpressionAdapter(methodSelector); base.NotifyImportsSatisfied(adapter.VerifyMethodInfo); return this; diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs index 44b0f727656728..a40a23f119d920 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/CompositionHost.cs @@ -41,8 +41,13 @@ public static CompositionHost CreateCompositionHost(params ExportDescriptorProvi /// Create the composition host. /// /// The container as an . - public static CompositionHost CreateCompositionHost(IEnumerable providers!!) + public static CompositionHost CreateCompositionHost(IEnumerable providers) { + if (providers is null) + { + throw new ArgumentNullException(nameof(providers)); + } + var allProviders = new ExportDescriptorProvider[] { new LazyExportDescriptorProvider(), new ExportFactoryExportDescriptorProvider(), diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs index 1bec402bf8faf4..1d1d0a38e34e75 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionDependency.cs @@ -37,8 +37,21 @@ public class CompositionDependency /// A marker used to identify the individual dependency among /// those on the dependent part. /// The contract required by the dependency. - public static CompositionDependency Satisfied(CompositionContract contract!!, ExportDescriptorPromise target!!, bool isPrerequisite, object site!!) + public static CompositionDependency Satisfied(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site) { + if (contract is null) + { + throw new ArgumentNullException(nameof(contract)); + } + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (site is null) + { + throw new ArgumentNullException(nameof(site)); + } + return new CompositionDependency(contract, target, isPrerequisite, site); } @@ -49,8 +62,17 @@ public static CompositionDependency Satisfied(CompositionContract contract!!, Ex /// A marker used to identify the individual dependency among /// those on the dependent part. /// The contract required by the dependency. - public static CompositionDependency Missing(CompositionContract contract!!, object site!!) + public static CompositionDependency Missing(CompositionContract contract, object site) { + if (contract is null) + { + throw new ArgumentNullException(nameof(contract)); + } + if (site is null) + { + throw new ArgumentNullException(nameof(site)); + } + return new CompositionDependency(contract, site); } @@ -62,8 +84,21 @@ public static CompositionDependency Missing(CompositionContract contract!!, obje /// those on the dependent part. /// The targets found when expecting only one. /// The contract required by the dependency. - public static CompositionDependency Oversupplied(CompositionContract contract!!, IEnumerable targets!!, object site!!) + public static CompositionDependency Oversupplied(CompositionContract contract, IEnumerable targets, object site) { + if (contract is null) + { + throw new ArgumentNullException(nameof(contract)); + } + if (targets is null) + { + throw new ArgumentNullException(nameof(targets)); + } + if (site is null) + { + throw new ArgumentNullException(nameof(site)); + } + return new CompositionDependency(contract, targets, site); } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs index aee870a0d404dd..c1fc011a93a07e 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/CompositionOperation.cs @@ -28,8 +28,17 @@ private CompositionOperation() { } /// to the parents of the context if required). /// Activator that will drive the operation. /// The composed object graph. - public static object Run(LifetimeContext outermostLifetimeContext!!, CompositeActivator compositionRootActivator!!) + public static object Run(LifetimeContext outermostLifetimeContext, CompositeActivator compositionRootActivator) { + if (outermostLifetimeContext is null) + { + throw new ArgumentNullException(nameof(outermostLifetimeContext)); + } + if (compositionRootActivator is null) + { + throw new ArgumentNullException(nameof(compositionRootActivator)); + } + using (var operation = new CompositionOperation()) { var result = compositionRootActivator(outermostLifetimeContext, operation); @@ -43,8 +52,13 @@ public static object Run(LifetimeContext outermostLifetimeContext!!, CompositeAc /// prerequisite part dependencies have been satisfied. /// /// Action to run. - public void AddNonPrerequisiteAction(Action action!!) + public void AddNonPrerequisiteAction(Action action) { + if (action is null) + { + throw new ArgumentNullException(nameof(action)); + } + if (_nonPrerequisiteActions == null) _nonPrerequisiteActions = new List(); @@ -56,8 +70,13 @@ public void AddNonPrerequisiteAction(Action action!!) /// all composition has completed. See OnImportsSatisfiedAttribute. /// /// Action to run. - public void AddPostCompositionAction(Action action!!) + public void AddPostCompositionAction(Action action) { + if (action is null) + { + throw new ArgumentNullException(nameof(action)); + } + if (_postCompositionActions == null) _postCompositionActions = new List(); diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs index 0bfcddd06ae001..4741349d399237 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/DirectExportDescriptor.cs @@ -10,8 +10,17 @@ internal sealed class DirectExportDescriptor : ExportDescriptor private readonly CompositeActivator _activator; private readonly IDictionary _metadata; - public DirectExportDescriptor(CompositeActivator activator!!, IDictionary metadata!!) + public DirectExportDescriptor(CompositeActivator activator, IDictionary metadata) { + if (activator is null) + { + throw new ArgumentNullException(nameof(activator)); + } + if (metadata is null) + { + throw new ArgumentNullException(nameof(metadata)); + } + _activator = activator; _metadata = metadata; } diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs index 55fb1829e834ce..863fccf11b85b9 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs @@ -8,14 +8,24 @@ namespace System.Composition.Hosting.Util { internal static class Formatters { - public static string ReadableList(IEnumerable items!!) + public static string ReadableList(IEnumerable items) { + if (items is null) + { + throw new ArgumentNullException(nameof(items)); + } + string reply = string.Join(SR.Formatter_ListSeparatorWithSpace, items.OrderBy(t => t)); return !string.IsNullOrEmpty(reply) ? reply : SR.Formatter_None; } - public static string Format(Type type!!) + public static string Format(Type type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + if (type.IsConstructedGenericType) { return FormatClosedGeneric(type); @@ -23,8 +33,13 @@ public static string Format(Type type!!) return type.Name; } - private static string FormatClosedGeneric(Type closedGenericType!!) + private static string FormatClosedGeneric(Type closedGenericType) { + if (closedGenericType is null) + { + throw new ArgumentNullException(nameof(closedGenericType)); + } + if (!closedGenericType.IsConstructedGenericType) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/ExportFactoryOfT.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/ExportFactoryOfT.cs index 7d94fa7fa954db..dabcc4491b5ad6 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/ExportFactoryOfT.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/ExportFactoryOfT.cs @@ -15,9 +15,9 @@ public class ExportFactory /// Construct an ExportFactory. /// /// Action invoked upon calls to the Create() method. - public ExportFactory(Func> exportCreator!!) + public ExportFactory(Func> exportCreator) { - _exportLifetimeContextCreator = exportCreator; + _exportLifetimeContextCreator = exportCreator ?? throw new ArgumentNullException(nameof(exportCreator)); } /// diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs index 68be062b230599..ebb14362686ecc 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Hosting/Core/CompositionContract.cs @@ -138,8 +138,13 @@ public CompositionContract ChangeType(Type newContractType) /// The value if it is present and of the correct type, otherwise null. /// The contract with the constraint removed if present, otherwise null. /// True if the constraint is present and of the correct type, otherwise false. - public bool TryUnwrapMetadataConstraint(string constraintName!!, out T constraintValue, out CompositionContract remainingContract) + public bool TryUnwrapMetadataConstraint(string constraintName, out T constraintValue, out CompositionContract remainingContract) { + if (constraintName is null) + { + throw new ArgumentNullException(nameof(constraintName)); + } + constraintValue = default(T); remainingContract = null; diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs index 6f510121afc879..2120fb035eb1e4 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs @@ -9,28 +9,21 @@ namespace System.Composition.Runtime.Util { internal static class Formatters { - public static string Format(object value!!) - { - if (value is string) - return "\"" + value + "\""; - - return value.ToString(); - } - - public static string Format(Type type) - { - if (type == null) throw new ArgumentNullException(nameof(type)); - - if (type.IsConstructedGenericType) - return FormatClosedGeneric(type); + public static string Format(object value) => + value is null ? throw new ArgumentNullException(nameof(value)) : + value is string ? $"\"{value}\"" : + value.ToString(); - return type.Name; - } + public static string Format(Type type) => + type is null ? throw new ArgumentNullException(nameof(type)) : + type.IsConstructedGenericType ? FormatClosedGeneric(type) : + type.Name; private static string FormatClosedGeneric(Type closedGenericType) { Debug.Assert(closedGenericType != null); Debug.Assert(closedGenericType.IsConstructedGenericType); + var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`')); IEnumerable args = closedGenericType.GenericTypeArguments.Select(t => Format(t)); return $"{name}<{string.Join(SR.Formatter_ListSeparatorWithSpace, args)}>"; diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs index 41b6d61b32fb42..624acc2027efa8 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs @@ -42,8 +42,21 @@ public static void SatisfyImports(this CompositionContext compositionContext, ob SatisfyImportsInternal(compositionContext, objectWithLooseImports, conventions); } - private static void SatisfyImportsInternal(this CompositionContext exportProvider!!, object objectWithLooseImports!!, AttributedModelProvider conventions!!) + private static void SatisfyImportsInternal(this CompositionContext exportProvider, object objectWithLooseImports, AttributedModelProvider conventions) { + if (exportProvider is null) + { + throw new ArgumentNullException(nameof(exportProvider)); + } + if (objectWithLooseImports is null) + { + throw new ArgumentNullException(nameof(objectWithLooseImports)); + } + if (conventions is null) + { + throw new ArgumentNullException(nameof(conventions)); + } + var objType = objectWithLooseImports.GetType(); foreach (var pi in objType.GetRuntimeProperties()) diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs index 7db5b2c541a5e2..b7efdca28c31dd 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/Hosting/ContainerConfiguration.cs @@ -47,8 +47,13 @@ public CompositionHost CreateContainer() /// /// An export descriptor provider. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider!!) + public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider) { + if (exportDescriptorProvider is null) + { + throw new ArgumentNullException(nameof(exportDescriptorProvider)); + } + _addedSources.Add(exportDescriptorProvider); return this; } @@ -60,8 +65,13 @@ public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescri /// /// /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions!!) + public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions) { + if (conventions is null) + { + throw new ArgumentNullException(nameof(conventions)); + } + if (_defaultAttributeContext != null) throw new InvalidOperationException(SR.ContainerConfiguration_DefaultConventionSet); @@ -145,8 +155,13 @@ public ContainerConfiguration WithParts(IEnumerable partTypes) /// The part types. /// Conventions represented by a , or null. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithParts(IEnumerable partTypes!!, AttributedModelProvider conventions) + public ContainerConfiguration WithParts(IEnumerable partTypes, AttributedModelProvider conventions) { + if (partTypes is null) + { + throw new ArgumentNullException(nameof(partTypes)); + } + _types.Add(Tuple.Create(partTypes, conventions)); return this; } @@ -192,8 +207,13 @@ public ContainerConfiguration WithAssemblies(IEnumerable assemblies) /// Assemblies containing part types. /// Conventions represented by a , or null. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithAssemblies(IEnumerable assemblies!!, AttributedModelProvider conventions) + public ContainerConfiguration WithAssemblies(IEnumerable assemblies, AttributedModelProvider conventions) { + if (assemblies is null) + { + throw new ArgumentNullException(nameof(assemblies)); + } + return WithParts(assemblies.SelectMany(a => a.DefinedTypes.Select(dt => dt.AsType())), conventions); } @@ -203,8 +223,13 @@ public ContainerConfiguration WithAssemblies(IEnumerable assemblies!!, /// The type of the contract of the instance. /// The instance to add to the container. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithExport(TExport exportedInstance!!) + public ContainerConfiguration WithExport(TExport exportedInstance) { + if (exportedInstance is null) + { + throw new ArgumentNullException(nameof(exportedInstance)); + } + return WithExport(exportedInstance, null, null); } @@ -216,8 +241,13 @@ public ContainerConfiguration WithExport(TExport exportedInstance!!) /// Optionally, a name that discriminates this contract from others with the same type. /// Optionally, a non-empty collection of named constraints that apply to the contract. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithExport(TExport exportedInstance!!, string contractName = null, IDictionary metadata = null) + public ContainerConfiguration WithExport(TExport exportedInstance, string contractName = null, IDictionary metadata = null) { + if (exportedInstance is null) + { + throw new ArgumentNullException(nameof(exportedInstance)); + } + return WithExport(typeof(TExport), exportedInstance, contractName, metadata); } @@ -227,8 +257,17 @@ public ContainerConfiguration WithExport(TExport exportedInstance!!, st /// The type of the contract of the instance. /// The instance to add to the container. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithExport(Type contractType!!, object exportedInstance!!) + public ContainerConfiguration WithExport(Type contractType, object exportedInstance) { + if (contractType is null) + { + throw new ArgumentNullException(nameof(contractType)); + } + if (exportedInstance is null) + { + throw new ArgumentNullException(nameof(exportedInstance)); + } + return WithExport(contractType, exportedInstance, null, null); } @@ -240,8 +279,17 @@ public ContainerConfiguration WithExport(Type contractType!!, object exportedIns /// Optionally, a name that discriminates this contract from others with the same type. /// Optionally, a non-empty collection of named constraints that apply to the contract. /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithExport(Type contractType!!, object exportedInstance!!, string contractName = null, IDictionary metadata = null) + public ContainerConfiguration WithExport(Type contractType, object exportedInstance, string contractName = null, IDictionary metadata = null) { + if (contractType is null) + { + throw new ArgumentNullException(nameof(contractType)); + } + if (exportedInstance is null) + { + throw new ArgumentNullException(nameof(exportedInstance)); + } + return WithProvider(new InstanceExportDescriptorProvider(exportedInstance, contractType, contractName, metadata)); } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs index 91e168e04b8212..25fe02e0ea94e2 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/ActivationFeatures/OnImportsSatisfiedFeature.cs @@ -19,8 +19,13 @@ internal sealed class OnImportsSatisfiedFeature : ActivationFeature { private readonly AttributedModelProvider _attributeContext; - public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext!!) + public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext) { + if (attributeContext is null) + { + throw new ArgumentNullException(nameof(attributeContext)); + } + _attributeContext = attributeContext; } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs index e3afc75a0ea9ee..23702ecfb27fb7 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Util/DirectAttributeContext.cs @@ -20,8 +20,13 @@ public override IEnumerable GetCustomAttributes(Type reflectedType, R return Attribute.GetCustomAttributes(member, false); } - public override IEnumerable GetCustomAttributes(Type reflectedType, Reflection.ParameterInfo parameter!!) + public override IEnumerable GetCustomAttributes(Type reflectedType, Reflection.ParameterInfo parameter) { + if (parameter is null) + { + throw new ArgumentNullException(nameof(parameter)); + } + if (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType)); return Attribute.GetCustomAttributes(parameter, false); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs index d8ef20ae594671..3123b43dc12380 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs @@ -28,8 +28,17 @@ public AppSettingsReader() /// throw an exception with a descriptive message so the user can make the appropriate /// change /// - public object GetValue(string key!!, Type type!!) + public object GetValue(string key, Type type) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + string val = _map[key]; if (val == null) throw new InvalidOperationException(SR.Format(SR.AppSettingsReaderNoKey, key)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs index 70606687d40dc4..384a4b14371d89 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -54,8 +54,13 @@ protected ApplicationSettingsBase(string settingsKey) /// /// Convenience overload that takes the owner component and settings key. /// - protected ApplicationSettingsBase(IComponent owner!!, string settingsKey) : this(settingsKey) + protected ApplicationSettingsBase(IComponent owner, string settingsKey) : this(settingsKey) { + if (owner is null) + { + throw new ArgumentNullException(nameof(owner)); + } + _owner = owner; if (owner.Site != null) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs index 0e2d926ef92411..d7ddeac8e3b84d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs @@ -15,8 +15,13 @@ public CallbackValidator(Type type, ValidatorCallback callback) : this(callback) } // Do not check for null type here to handle the callback attribute case - internal CallbackValidator(ValidatorCallback callback!!) + internal CallbackValidator(ValidatorCallback callback) { + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + _type = null; _callback = callback; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs index 9f00b30f51802a..7ef7a7270e3af2 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs @@ -29,8 +29,13 @@ public abstract class ConfigurationElementCollection : ConfigurationElement, ICo protected ConfigurationElementCollection() { } - protected ConfigurationElementCollection(IComparer comparer!!) + protected ConfigurationElementCollection(IComparer comparer) { + if (comparer is null) + { + throw new ArgumentNullException(nameof(comparer)); + } + _comparer = comparer; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs index 78449e58857c29..51cf83f32819c4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs @@ -9,8 +9,13 @@ namespace System.Configuration // new overridable on ConfigurationElement public sealed class ConfigurationElementProperty { - public ConfigurationElementProperty(ConfigurationValidatorBase validator!!) + public ConfigurationElementProperty(ConfigurationValidatorBase validator) { + if (validator is null) + { + throw new ArgumentNullException(nameof(validator)); + } + Validator = validator; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs index d6cbe437a04253..63442362d902db 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs @@ -68,8 +68,13 @@ public void Clear() foreach (string key in allKeys) Remove(key); } - public void CopyTo(ConfigurationSection[] array!!, int index) + public void CopyTo(ConfigurationSection[] array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + int c = Count; if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs index 253c360983e0f3..68157107c77a7e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs @@ -65,8 +65,13 @@ public void Clear() foreach (string key in allKeys) Remove(key); } - public void CopyTo(ConfigurationSectionGroup[] array!!, int index) + public void CopyTo(ConfigurationSectionGroup[] array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + int c = Count; if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs index cd6f9f1aff0e57..3af31a63f0e72d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs @@ -10,8 +10,13 @@ public override bool CanValidate(Type type) return type == typeof(TimeSpan); } - public override void Validate(object value!!) + public override void Validate(object value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if ((TimeSpan)value <= TimeSpan.Zero) throw new ArgumentException(SR.Validator_timespan_value_must_be_positive); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs index 23c4a0e8aaec0d..9547bc96fb5f90 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs @@ -39,8 +39,13 @@ public PropertyInformation this[string propertyName] internal PropertyInformation this[int index] => (PropertyInformation)BaseGet(BaseGetKey(index)); - public void CopyTo(PropertyInformation[] array!!, int index) + public void CopyTo(PropertyInformation[] array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Length < Count + index) throw new ArgumentOutOfRangeException(nameof(index)); foreach (PropertyInformation pi in this) array[index++] = pi; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs index a386057906d0f4..3db1a0602624f2 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs @@ -9,8 +9,13 @@ public class ProtectedConfigurationProviderCollection : ProviderCollection { public new ProtectedConfigurationProvider this[string name] => (ProtectedConfigurationProvider)base[name]; - public override void Add(ProviderBase provider!!) + public override void Add(ProviderBase provider) { + if (provider is null) + { + throw new ArgumentNullException(nameof(provider)); + } + if (!(provider is ProtectedConfigurationProvider)) { throw new ArgumentException( diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs index 4f667ff1435543..9cdf0d00fce722 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs @@ -7,8 +7,13 @@ namespace System.Configuration { public class SettingsProviderCollection : ProviderCollection { - public override void Add(ProviderBase provider!!) + public override void Add(ProviderBase provider) { + if (provider is null) + { + throw new ArgumentNullException(nameof(provider)); + } + if (!(provider is SettingsProvider)) { throw new ArgumentException(SR.Format(SR.Config_provider_must_implement_type, typeof(SettingsProvider)), nameof(provider)); diff --git a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs index 380257a8af92eb..aa9fe7f2264621 100644 --- a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs +++ b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs @@ -115,8 +115,10 @@ public override Task ReadToEndAsync(CancellationToken cancellationToken) Task.FromResult(ReadToEnd()); } - public override Task ReadBlockAsync(char[] buffer!!, int index, int count) + public override Task ReadBlockAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) @@ -125,8 +127,10 @@ public override Task ReadBlockAsync(char[] buffer!!, int index, int count) return Task.FromResult(ReadBlock(buffer, index, count)); } - public override Task ReadAsync(char[] buffer!!, int index, int count) + public override Task ReadAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) diff --git a/src/libraries/System.Console/src/System/TermInfo.cs b/src/libraries/System.Console/src/System/TermInfo.cs index 02a4971b93fd45..1f7d67188c882b 100644 --- a/src/libraries/System.Console/src/System/TermInfo.cs +++ b/src/libraries/System.Console/src/System/TermInfo.cs @@ -559,8 +559,11 @@ public static string Evaluate(string format, FormatParam arg1, FormatParam arg2) /// The format string. /// The arguments to the format string. /// The formatted string. - public static string Evaluate(string format!!, params FormatParam[] args!!) + public static string Evaluate(string format, params FormatParam[] args) { + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(args); + // Initialize the stack to use for processing. Stack? stack = t_cachedStack; if (stack == null) diff --git a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs index f85ce5a2385942..c696f7d92bdaf8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs @@ -68,8 +68,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "InstanceDescriptor calls GetType(string) on AssemblyQualifiedName of instance of type we already have in here.")] - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string)) { return value != null ? value.ToString() : string.Empty; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs index 307622604f8ad0..a4a28c95bd228d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs @@ -52,8 +52,10 @@ private void PopulateFields() private T? GetDbColumnValue(string columnName) => _schemaColumns.Contains(columnName) && _schemaRow[columnName] is T value ? value : default; } - public static ReadOnlyCollection GetColumnSchema(this DbDataReader reader!!) + public static ReadOnlyCollection GetColumnSchema(this DbDataReader reader) { + ArgumentNullException.ThrowIfNull(reader); + if (reader is IDbColumnSchemaGenerator schemaGenerator) { return schemaGenerator.GetColumnSchema(); diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs index 472ed3c6c4f41e..407125f8d43e50 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs @@ -28,8 +28,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// type is string. If this cannot convert to the destination type, this will /// throw a NotSupportedException. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(InstanceDescriptor) && value is Constraint) { if (value is UniqueConstraint) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs index 62f7cb08d8b92a..4f06655e706c9a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs @@ -11,136 +11,188 @@ namespace System.Data { public static class DataReaderExtensions { - public static bool GetBoolean(this DbDataReader reader!!, string name) + public static bool GetBoolean(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetBoolean(reader.GetOrdinal(name)); } - public static byte GetByte(this DbDataReader reader!!, string name) + public static byte GetByte(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetByte(reader.GetOrdinal(name)); } - public static long GetBytes(this DbDataReader reader!!, string name, long dataOffset, byte[] buffer, int bufferOffset, int length) + public static long GetBytes(this DbDataReader reader, string name, long dataOffset, byte[] buffer, int bufferOffset, int length) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetBytes(reader.GetOrdinal(name), dataOffset, buffer, bufferOffset, length); } - public static char GetChar(this DbDataReader reader!!, string name) + public static char GetChar(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetChar(reader.GetOrdinal(name)); } - public static long GetChars(this DbDataReader reader!!, string name, long dataOffset, char[] buffer, int bufferOffset, int length) + public static long GetChars(this DbDataReader reader, string name, long dataOffset, char[] buffer, int bufferOffset, int length) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetChars(reader.GetOrdinal(name), dataOffset, buffer, bufferOffset, length); } [EditorBrowsable(EditorBrowsableState.Never)] - public static DbDataReader GetData(this DbDataReader reader!!, string name) + public static DbDataReader GetData(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetData(reader.GetOrdinal(name)); } - public static string GetDataTypeName(this DbDataReader reader!!, string name) + public static string GetDataTypeName(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetDataTypeName(reader.GetOrdinal(name)); } - public static DateTime GetDateTime(this DbDataReader reader!!, string name) + public static DateTime GetDateTime(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetDateTime(reader.GetOrdinal(name)); } - public static decimal GetDecimal(this DbDataReader reader!!, string name) + public static decimal GetDecimal(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetDecimal(reader.GetOrdinal(name)); } - public static double GetDouble(this DbDataReader reader!!, string name) + public static double GetDouble(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetDouble(reader.GetOrdinal(name)); } - public static Type GetFieldType(this DbDataReader reader!!, string name) + public static Type GetFieldType(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetFieldType(reader.GetOrdinal(name)); } - public static T GetFieldValue(this DbDataReader reader!!, string name) + public static T GetFieldValue(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetFieldValue(reader.GetOrdinal(name)); } - public static Task GetFieldValueAsync(this DbDataReader reader!!, string name, CancellationToken cancellationToken = default(CancellationToken)) + public static Task GetFieldValueAsync(this DbDataReader reader, string name, CancellationToken cancellationToken = default(CancellationToken)) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetFieldValueAsync(reader.GetOrdinal(name), cancellationToken); } - public static float GetFloat(this DbDataReader reader!!, string name) + public static float GetFloat(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetFloat(reader.GetOrdinal(name)); } - public static Guid GetGuid(this DbDataReader reader!!, string name) + public static Guid GetGuid(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetGuid(reader.GetOrdinal(name)); } - public static short GetInt16(this DbDataReader reader!!, string name) + public static short GetInt16(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetInt16(reader.GetOrdinal(name)); } - public static int GetInt32(this DbDataReader reader!!, string name) + public static int GetInt32(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetInt32(reader.GetOrdinal(name)); } - public static long GetInt64(this DbDataReader reader!!, string name) + public static long GetInt64(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetInt64(reader.GetOrdinal(name)); } [EditorBrowsable(EditorBrowsableState.Never)] - public static Type GetProviderSpecificFieldType(this DbDataReader reader!!, string name) + public static Type GetProviderSpecificFieldType(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetProviderSpecificFieldType(reader.GetOrdinal(name)); } [EditorBrowsable(EditorBrowsableState.Never)] - public static object GetProviderSpecificValue(this DbDataReader reader!!, string name) + public static object GetProviderSpecificValue(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetProviderSpecificValue(reader.GetOrdinal(name)); } - public static Stream GetStream(this DbDataReader reader!!, string name) + public static Stream GetStream(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetStream(reader.GetOrdinal(name)); } - public static string GetString(this DbDataReader reader!!, string name) + public static string GetString(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetString(reader.GetOrdinal(name)); } - public static TextReader GetTextReader(this DbDataReader reader!!, string name) + public static TextReader GetTextReader(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetTextReader(reader.GetOrdinal(name)); } - public static object GetValue(this DbDataReader reader!!, string name) + public static object GetValue(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.GetValue(reader.GetOrdinal(name)); } - public static bool IsDBNull(this DbDataReader reader!!, string name) + public static bool IsDBNull(this DbDataReader reader, string name) { + ArgumentNullException.ThrowIfNull(reader); + return reader.IsDBNull(reader.GetOrdinal(name)); } - public static Task IsDBNullAsync(this DbDataReader reader!!, string name, CancellationToken cancellationToken = default(CancellationToken)) + public static Task IsDBNullAsync(this DbDataReader reader, string name, CancellationToken cancellationToken = default(CancellationToken)) { + ArgumentNullException.ThrowIfNull(reader); + return reader.IsDBNullAsync(reader.GetOrdinal(name), cancellationToken); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs index db60ac28bf6baa..ff9b5a7e3f898f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs @@ -19,8 +19,10 @@ public DefaultValueTypeConverter() { } - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == typeof(string)) { if (value == null) diff --git a/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs b/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs index 98753815b0cd8f..bc82e2f7489b9e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs @@ -20,8 +20,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( destinationType == typeof(string) || base.CanConvertTo(context, destinationType); - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + return destinationType == typeof(string) ? Array.Empty().GetType().Name : base.ConvertTo(context, culture, value, destinationType); diff --git a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs index 572af63fc29483..506c4aa5fa6222 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs @@ -35,8 +35,10 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( /// type is string. If this cannot convert to the destination type, this will /// throw a NotSupportedException. /// - public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + System.Reflection.ConstructorInfo? ctor; object[]? values; diff --git a/src/libraries/System.Data.OleDb/src/OleDbException.cs b/src/libraries/System.Data.OleDb/src/OleDbException.cs index 564cc463ead286..3a562dc7a80bcb 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbException.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbException.cs @@ -35,8 +35,10 @@ private OleDbException(string? message, Exception? inner, string? source, OleDbH this.oledbErrors = errors; } - public override void GetObjectData(SerializationInfo si!!, StreamingContext context) + public override void GetObjectData(SerializationInfo si, StreamingContext context) { + ArgumentNullException.ThrowIfNull(si); + si.AddValue("oledbErrors", oledbErrors, typeof(OleDbErrorCollection)); base.GetObjectData(si, context); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs index e20d26dfd9ad21..55cacc67053ea3 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs @@ -94,8 +94,13 @@ public static bool TryParse(string? traceParent, string? traceState, bool isRemo /// /// The ActivityContext object created from the parsing operation. /// - public static ActivityContext Parse(string traceParent!!, string? traceState) + public static ActivityContext Parse(string traceParent, string? traceState) { + if (traceParent is null) + { + throw new ArgumentNullException(nameof(traceParent)); + } + if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out ActivityContext context)) { throw new ArgumentException(SR.InvalidTraceParent); diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs index a923d8b18a3e9e..7cf9d46327a12d 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs @@ -18,9 +18,9 @@ public sealed class ActivitySource : IDisposable /// /// The name of the ActivitySource object /// The version of the component publishing the tracing info. - public ActivitySource(string name!!, string? version = "") + public ActivitySource(string name, string? version = "") { - Name = name; + Name = name ?? throw new ArgumentNullException(nameof(name)); Version = version; s_activeSources.Add(this); @@ -303,8 +303,13 @@ public void Dispose() /// Add a listener to the starting and stopping events. /// /// The object to use for listening to the events. - public static void AddActivityListener(ActivityListener listener!!) + public static void AddActivityListener(ActivityListener listener) { + if (listener is null) + { + throw new ArgumentNullException(nameof(listener)); + } + if (s_allListeners.AddIfNotExist(listener)) { s_activeSources.EnumWithAction((source, obj) => { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs index cd45fcb0a2bc0d..f009edcee6c25b 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs @@ -34,8 +34,13 @@ public ActivityTagsCollection() /// Create a new instance of the collection and store the input list items in the collection. /// /// Initial list to store in the collection. - public ActivityTagsCollection(IEnumerable> list!!) + public ActivityTagsCollection(IEnumerable> list) { + if (list is null) + { + throw new ArgumentNullException(nameof(list)); + } + foreach (KeyValuePair kvp in list) { if (kvp.Key != null) @@ -137,8 +142,13 @@ public ICollection Values /// /// The tag key. /// The tag value. - public void Add(string key!!, object? value) + public void Add(string key, object? value) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + int index = FindIndex(key); if (index >= 0) { @@ -209,8 +219,13 @@ public void Add(KeyValuePair item) /// /// The tag key /// True if the item existed and removed. False otherwise. - public bool Remove(string key!!) + public bool Remove(string key) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + int index = FindIndex(key); if (index >= 0) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Instrument.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Instrument.cs index 14bc09e190516d..4d16ef4bb99470 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Instrument.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Instrument.cs @@ -37,10 +37,10 @@ public abstract class Instrument /// The instrument name. cannot be null. /// Optional instrument unit of measurements. /// Optional instrument description. - protected Instrument(Meter meter!!, string name!!, string? unit, string? description) + protected Instrument(Meter meter, string name, string? unit, string? description) { - Meter = meter; - Name = name; + Meter = meter ?? throw new ArgumentNullException(nameof(meter)); + Name = name ?? throw new ArgumentNullException(nameof(name)); Description = description; Unit = unit; } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs index 201f8242b50552..8332e5de79d8eb 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/Meter.cs @@ -30,9 +30,9 @@ public Meter(string name) : this (name, null) {} /// /// The Meter name. /// The optional Meter version. - public Meter(string name!!, string? version) + public Meter(string name, string? version) { - Name = name; + Name = name ?? throw new ArgumentNullException(nameof(name)); Version = version; lock (Instrument.SyncObject) diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableCounter.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableCounter.cs index 7815496f00a7bc..4a360a25082133 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableCounter.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableCounter.cs @@ -20,21 +20,21 @@ public sealed class ObservableCounter : ObservableInstrument where T : str { private object _callback; - internal ObservableCounter(Meter meter, string name, Func observeValue!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableCounter(Meter meter, string name, Func observeValue, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValue; + _callback = observeValue ?? throw new ArgumentNullException(nameof(observeValue)); Publish(); } - internal ObservableCounter(Meter meter, string name, Func> observeValue!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableCounter(Meter meter, string name, Func> observeValue, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValue; + _callback = observeValue ?? throw new ArgumentNullException(nameof(observeValue)); Publish(); } - internal ObservableCounter(Meter meter, string name, Func>> observeValues!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableCounter(Meter meter, string name, Func>> observeValues, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValues; + _callback = observeValues ?? throw new ArgumentNullException(nameof(observeValues)); Publish(); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableGauge.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableGauge.cs index 258351c494b869..f73845a1148443 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableGauge.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableGauge.cs @@ -20,21 +20,21 @@ public sealed class ObservableGauge : ObservableInstrument where T : struc { private object _callback; - internal ObservableGauge(Meter meter, string name, Func observeValue!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableGauge(Meter meter, string name, Func observeValue, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValue; + _callback = observeValue ?? throw new ArgumentNullException(nameof(observeValue)); Publish(); } - internal ObservableGauge(Meter meter, string name, Func> observeValue!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableGauge(Meter meter, string name, Func> observeValue, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValue; + _callback = observeValue ?? throw new ArgumentNullException(nameof(observeValue)); Publish(); } - internal ObservableGauge(Meter meter, string name, Func>> observeValues!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableGauge(Meter meter, string name, Func>> observeValues, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValues; + _callback = observeValues ?? throw new ArgumentNullException(nameof(observeValues)); Publish(); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableUpDownCounter.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableUpDownCounter.cs index 82d75dabb4dcd7..32ea7255ba4063 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableUpDownCounter.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableUpDownCounter.cs @@ -20,21 +20,21 @@ public sealed class ObservableUpDownCounter : ObservableInstrument where T { private object _callback; - internal ObservableUpDownCounter(Meter meter, string name, Func observeValue!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableUpDownCounter(Meter meter, string name, Func observeValue, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValue; + _callback = observeValue ?? throw new ArgumentNullException(nameof(observeValue)); Publish(); } - internal ObservableUpDownCounter(Meter meter, string name, Func> observeValue!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableUpDownCounter(Meter meter, string name, Func> observeValue, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValue; + _callback = observeValue ?? throw new ArgumentNullException(nameof(observeValue)); Publish(); } - internal ObservableUpDownCounter(Meter meter, string name, Func>> observeValues!!, string? unit, string? description) : base(meter, name, unit, description) + internal ObservableUpDownCounter(Meter meter, string name, Func>> observeValues, string? unit, string? description) : base(meter, name, unit, description) { - _callback = observeValues; + _callback = observeValues ?? throw new ArgumentNullException(nameof(observeValues)); Publish(); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.cs index 0b8b00e316cedb..fb8d1027b4a29f 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/TagList.cs @@ -261,8 +261,13 @@ public readonly void CopyTo(Span> tags) /// The zero-based index in at which copying begins. /// is null. /// is less than 0 or greater that or equal the length. - public readonly void CopyTo(KeyValuePair[] array!!, int arrayIndex) + public readonly void CopyTo(KeyValuePair[] array, int arrayIndex) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if ((uint)arrayIndex >= array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex)); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index 3cf5c9e1b1dcfd..e24ce1fef4ced0 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -243,8 +243,10 @@ public static void CreateEventSource(string source, string logName, string machi CreateEventSource(new EventSourceCreationData(source, logName, machineName)); } - public static void CreateEventSource(EventSourceCreationData sourceData!!) + public static void CreateEventSource(EventSourceCreationData sourceData) { + ArgumentNullException.ThrowIfNull(sourceData); + string logName = sourceData.LogName; string source = sourceData.Source; string machineName = sourceData.MachineName; diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index 3a67a6ead1810c..686329d8ec4e81 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -109,8 +109,10 @@ public EventLogInternal(string logName, string machineName, string source) : thi { } - public EventLogInternal(string logName!!, string machineName, string source, EventLog parent) + public EventLogInternal(string logName, string machineName, string source, EventLog parent) { + ArgumentNullException.ThrowIfNull(logName); + if (!ValidLogName(logName, true)) throw new ArgumentException(SR.BadLogName); @@ -130,9 +132,7 @@ public EventLogEntryCollection Entries { get { - if (entriesCollection == null) - entriesCollection = new EventLogEntryCollection(this); - return entriesCollection; + return entriesCollection ??= new EventLogEntryCollection(this); } } @@ -195,13 +195,14 @@ public string LogDisplayName string resourceDll = (string)logkey.GetValue("DisplayNameFile"); if (resourceDll == null) + { logDisplayName = GetLogName(currentMachineName); + } else { int resourceId = (int)logkey.GetValue("DisplayNameID"); logDisplayName = FormatMessageWrapper(resourceDll, (uint)resourceId, null); - if (logDisplayName == null) - logDisplayName = GetLogName(currentMachineName); + logDisplayName ??= GetLogName(currentMachineName); } } finally @@ -225,7 +226,7 @@ public string Log private string GetLogName(string currentMachineName) { - if ((logName == null || logName.Length == 0) && sourceName != null && sourceName.Length != 0) + if (string.IsNullOrEmpty(logName) && !string.IsNullOrEmpty(sourceName)) { logName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName); } @@ -276,9 +277,7 @@ internal Hashtable MessageLibraries { get { - if (messageLibraries == null) - messageLibraries = new Hashtable(StringComparer.OrdinalIgnoreCase); - return messageLibraries; + return messageLibraries ??= new Hashtable(StringComparer.OrdinalIgnoreCase); } } @@ -647,15 +646,14 @@ internal string FormatMessageWrapper(string dllNameList, uint messageNum, string if (dllNameList == null) return null; - if (insertionStrings == null) - insertionStrings = Array.Empty(); + insertionStrings ??= Array.Empty(); string[] listDll = dllNameList.Split(';'); // Find first mesage in DLL list foreach (string dllName in listDll) { - if (dllName == null || dllName.Length == 0) + if (string.IsNullOrEmpty(dllName)) continue; SafeLibraryHandle hModule; @@ -1046,7 +1044,7 @@ private void OpenForRead(string currentMachineName) string logname = GetLogName(currentMachineName); - if (logname == null || logname.Length == 0) + if (string.IsNullOrEmpty(logname)) throw new ArgumentException(SR.MissingLogProperty); if (!EventLog.Exists(logname, currentMachineName)) // do not open non-existing Log [alexvec] @@ -1080,7 +1078,7 @@ private void OpenForWrite(string currentMachineName) if (this.boolFlags[Flag_disposed]) throw new ObjectDisposedException(GetType().Name); - if (sourceName == null || sourceName.Length == 0) + if (string.IsNullOrEmpty(sourceName)) throw new ArgumentException(SR.NeedSourceToOpen); SafeEventLogWriteHandle handle = Interop.Advapi32.RegisterEventSource(currentMachineName, sourceName); @@ -1311,8 +1309,10 @@ public void WriteEntry(string message, EventLogEntryType type, int eventID, shor InternalWriteEvent((uint)eventID, (ushort)category, type, new string[] { message }, rawData, currentMachineName); } - public void WriteEvent(EventInstance instance!!, byte[] data, params object[] values) + public void WriteEvent(EventInstance instance, byte[] data, params object[] values) { + ArgumentNullException.ThrowIfNull(instance); + if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); @@ -1344,24 +1344,20 @@ public void WriteEvent(EventInstance instance!!, byte[] data, params object[] va private void InternalWriteEvent(uint eventID, ushort category, EventLogEntryType type, string[] strings, byte[] rawData, string currentMachineName) { - // check arguments - if (strings == null) - strings = Array.Empty(); + strings ??= Array.Empty(); if (strings.Length >= 256) throw new ArgumentException(SR.TooManyReplacementStrings); for (int i = 0; i < strings.Length; i++) { - if (strings[i] == null) - strings[i] = string.Empty; + strings[i] ??= string.Empty; // make sure the strings aren't too long. MSDN says each string has a limit of 32k (32768) characters, but // experimentation shows that it doesn't like anything larger than 32766 if (strings[i].Length > 32766) throw new ArgumentException(SR.LogEntryTooLong); } - if (rawData == null) - rawData = Array.Empty(); + rawData ??= Array.Empty(); if (Source.Length == 0) throw new ArgumentException(SR.NeedSourceToWrite); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventBookmark.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventBookmark.cs index 55e01f5f1149ff..246777f293bcdc 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventBookmark.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventBookmark.cs @@ -17,8 +17,10 @@ namespace System.Diagnostics.Eventing.Reader /// public class EventBookmark { - internal EventBookmark(string bookmarkText!!) + internal EventBookmark(string bookmarkText) { + ArgumentNullException.ThrowIfNull(bookmarkText); + BookmarkText = bookmarkText; } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs index ea815291cbf67b..f16e8fc1328203 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogPropertySelector.cs @@ -13,8 +13,10 @@ namespace System.Diagnostics.Eventing.Reader /// public class EventLogPropertySelector : IDisposable { - public EventLogPropertySelector(IEnumerable propertyQueries!!) + public EventLogPropertySelector(IEnumerable propertyQueries) { + ArgumentNullException.ThrowIfNull(propertyQueries); + string[] paths; ICollection coll = propertyQueries as ICollection; diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs index b56215642aa9fb..c7a0b6b8ed1adf 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs @@ -62,8 +62,10 @@ public EventLogReader(EventLogQuery eventQuery) { } - public EventLogReader(EventLogQuery eventQuery!!, EventBookmark bookmark) + public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) { + ArgumentNullException.ThrowIfNull(eventQuery); + string logfile = null; if (eventQuery.ThePathType == PathType.FilePath) logfile = eventQuery.Path; @@ -228,8 +230,10 @@ public void Seek(EventBookmark bookmark) Seek(bookmark, 0); } - public void Seek(EventBookmark bookmark!!, long offset) + public void Seek(EventBookmark bookmark, long offset) { + ArgumentNullException.ThrowIfNull(bookmark); + SeekReset(); using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark)) { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs index 136daa04cb9d71..a197659a2f3f26 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogRecord.cs @@ -389,8 +389,10 @@ public override IList Properties } } - public IList GetPropertyValues(EventLogPropertySelector propertySelector!!) + public IList GetPropertyValues(EventLogPropertySelector propertySelector) { + ArgumentNullException.ThrowIfNull(propertySelector); + return NativeWrapper.EvtRenderBufferWithContextUserOrValues(propertySelector.Handle, Handle); } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs index be9edaa67d88a6..31bfdf8ac94294 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs @@ -203,8 +203,10 @@ public IEnumerable GetLogNames() } } - public EventLogInformation GetLogInformation(string logName!!, PathType pathType) + public EventLogInformation GetLogInformation(string logName, PathType pathType) { + ArgumentNullException.ThrowIfNull(logName); + return new EventLogInformation(this, logName, pathType); } @@ -213,8 +215,11 @@ public void ExportLog(string path, PathType pathType, string query, string targe this.ExportLog(path, pathType, query, targetFilePath, false); } - public void ExportLog(string path!!, PathType pathType, string query, string targetFilePath!!, bool tolerateQueryErrors) + public void ExportLog(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors) { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(targetFilePath); + UnsafeNativeMethods.EvtExportLogFlags flag = pathType switch { PathType.LogName => UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogChannelPath, @@ -244,8 +249,10 @@ public void ClearLog(string logName) this.ClearLog(logName, null); } - public void ClearLog(string logName!!, string backupPath) + public void ClearLog(string logName, string backupPath) { + ArgumentNullException.ThrowIfNull(logName); + NativeWrapper.EvtClearLog(this.Handle, logName, backupPath, 0); } } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs index 1d2994f0b4ff6e..112b1fa2bbf844 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogWatcher.cs @@ -49,8 +49,10 @@ public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark) { } - public EventLogWatcher(EventLogQuery eventQuery!!, EventBookmark bookmark, bool readExistingEvents) + public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark, bool readExistingEvents) { + ArgumentNullException.ThrowIfNull(eventQuery); + if (bookmark != null) { readExistingEvents = false; diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs index 98f40d1df1cba4..f44cab190e1aa7 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs @@ -39,16 +39,20 @@ public int Add(CounterCreationData value) return List.Add(value); } - public void AddRange(CounterCreationData[] value!!) + public void AddRange(CounterCreationData[] value) { + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CounterCreationDataCollection value!!) + public void AddRange(CounterCreationDataCollection value) { + ArgumentNullException.ThrowIfNull(value); + int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { @@ -81,8 +85,10 @@ public virtual void Remove(CounterCreationData value) List.Remove(value); } - protected override void OnValidate(object value!!) + protected override void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is CounterCreationData)) throw new ArgumentException(SR.MustAddCounterCreationData); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs index 1e9d53b49216f2..17cbebb73b733b 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs @@ -15,8 +15,10 @@ namespace System.Diagnostics public class InstanceDataCollection : DictionaryBase { [Obsolete("This constructor has been deprecated. Use System.Diagnostics.InstanceDataCollectionCollection.get_Item to get an instance of this collection instead.")] - public InstanceDataCollection(string counterName!!) + public InstanceDataCollection(string counterName) { + ArgumentNullException.ThrowIfNull(counterName); + CounterName = counterName; } @@ -56,8 +58,10 @@ internal void Add(string instanceName, InstanceData value) Dictionary.Add(objectName, value); } - public bool Contains(string instanceName!!) + public bool Contains(string instanceName) { + ArgumentNullException.ThrowIfNull(instanceName); + string objectName = instanceName.ToLowerInvariant(); return Dictionary.Contains(objectName); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs index ad556f300c76e4..3b34da2b433574 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs @@ -49,8 +49,10 @@ internal void Add(string counterName, InstanceDataCollection value) Dictionary.Add(objectName, value); } - public bool Contains(string counterName!!) + public bool Contains(string counterName) { + ArgumentNullException.ThrowIfNull(counterName); + object objectName = counterName.ToLowerInvariant(); return Dictionary.Contains(objectName); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs index 727dce4931188c..d92a6bb32a16e1 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs @@ -41,8 +41,10 @@ public PerformanceCounterCategory(string categoryName) /// Creates a PerformanceCounterCategory object for given category. /// Uses the given machine name. /// - public PerformanceCounterCategory(string categoryName!!, string machineName) + public PerformanceCounterCategory(string categoryName, string machineName) { + ArgumentNullException.ThrowIfNull(categoryName); + if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); @@ -147,8 +149,10 @@ public string MachineName /// /// Returns true if the counter is registered for this category /// - public bool CounterExists(string counterName!!) + public bool CounterExists(string counterName) { + ArgumentNullException.ThrowIfNull(counterName); + if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); @@ -166,8 +170,11 @@ public static bool CounterExists(string counterName, string categoryName) /// /// Returns true if the counter is registered for this category on a particular machine. /// - public static bool CounterExists(string counterName!!, string categoryName!!, string machineName) + public static bool CounterExists(string counterName, string categoryName, string machineName) { + ArgumentNullException.ThrowIfNull(counterName); + ArgumentNullException.ThrowIfNull(categoryName); + if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); @@ -242,8 +249,10 @@ public static PerformanceCounterCategory Create(string categoryName, string cate } // there is an idential copy of CheckValidCategory in PerformnaceCounterInstaller - internal static void CheckValidCategory(string categoryName!!) + internal static void CheckValidCategory(string categoryName) { + ArgumentNullException.ThrowIfNull(categoryName); + if (!CheckValidId(categoryName, MaxCategoryNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCategoryName, 1, MaxCategoryNameLength)); @@ -253,8 +262,10 @@ internal static void CheckValidCategory(string categoryName!!) throw new ArgumentException(SR.CategoryNameTooLong); } - internal static void CheckValidCounter(string counterName!!) + internal static void CheckValidCounter(string counterName) { + ArgumentNullException.ThrowIfNull(counterName); + if (!CheckValidId(counterName, MaxCounterNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCounterName, 1, MaxCounterNameLength)); } @@ -282,8 +293,10 @@ internal static bool CheckValidId(string id, int maxLength) return true; } - internal static void CheckValidHelp(string help!!) + internal static void CheckValidHelp(string help) { + ArgumentNullException.ThrowIfNull(help); + if (help.Length > MaxHelpLength) throw new ArgumentException(SR.Format(SR.PerfInvalidHelp, 0, MaxHelpLength)); } @@ -401,8 +414,10 @@ public static bool Exists(string categoryName) /// /// Returns true if the category is registered in the machine. /// - public static bool Exists(string categoryName!!, string machineName) + public static bool Exists(string categoryName, string machineName) { + ArgumentNullException.ThrowIfNull(categoryName); + if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); @@ -448,8 +463,10 @@ public PerformanceCounter[] GetCounters() /// /// Returns an array of counters in this category for the given instance. /// - public PerformanceCounter[] GetCounters(string instanceName!!) + public PerformanceCounter[] GetCounters(string instanceName) { + ArgumentNullException.ThrowIfNull(instanceName); + if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); @@ -503,8 +520,10 @@ public string[] GetInstanceNames() /// /// Returns true if the instance already exists for this category. /// - public bool InstanceExists(string instanceName!!) + public bool InstanceExists(string instanceName) { + ArgumentNullException.ThrowIfNull(instanceName); + if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); @@ -525,8 +544,11 @@ public static bool InstanceExists(string instanceName, string categoryName) /// /// Returns true if the instance already exists for this category and machine specified. /// - public static bool InstanceExists(string instanceName!!, string categoryName!!, string machineName) + public static bool InstanceExists(string instanceName, string categoryName, string machineName) { + ArgumentNullException.ThrowIfNull(instanceName); + ArgumentNullException.ThrowIfNull(categoryName); + if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs index e2e2021d52ed42..e4c7e6f8c22a58 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs @@ -124,8 +124,10 @@ public void AddCounter(int counterId, CounterType counterType) /// CounterId uniquely identifies the counter within CounterSet /// One of defined CounterType values /// This is friendly name to help provider developers as indexer. and it might not match what is displayed in counter consumption applications lie perfmon. - public void AddCounter(int counterId, CounterType counterType, string counterName!!) + public void AddCounter(int counterId, CounterType counterType, string counterName) { + ArgumentNullException.ThrowIfNull(counterName); + if (counterName.Length == 0) { throw new ArgumentException(SR.Perflib_Argument_EmptyCounterName, nameof(counterName)); @@ -168,8 +170,10 @@ public void AddCounter(int counterId, CounterType counterType, string counterNam /// /// Friendly name identifies the instance. InstanceName would be shown in counter consumption applications like perfmon. /// CounterSetInstance object - public CounterSetInstance CreateCounterSetInstance(string instanceName!!) + public CounterSetInstance CreateCounterSetInstance(string instanceName) { + ArgumentNullException.ThrowIfNull(instanceName); + if (instanceName.Length == 0) { throw new ArgumentException(SR.Perflib_Argument_EmptyInstanceName, nameof(instanceName)); diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs index 4b5782bd322a65..a1f12783eb611f 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstance.cs @@ -17,8 +17,11 @@ public sealed class CounterSetInstance : IDisposable private int _active; internal unsafe Interop.PerfCounter.PerfCounterSetInstanceStruct* _nativeInst; - internal unsafe CounterSetInstance(CounterSet counterSetDefined!!, string instanceName!!) + internal unsafe CounterSetInstance(CounterSet counterSetDefined, string instanceName) { + ArgumentNullException.ThrowIfNull(counterSetDefined); + ArgumentNullException.ThrowIfNull(instanceName); + if (instanceName.Length == 0) { throw new ArgumentException(SR.Perflib_Argument_EmptyInstanceName, nameof(instanceName)); diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs index 7fee3aa86ac151..8e07cd69133810 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs @@ -221,14 +221,20 @@ public CounterData this[int counterId] /// /// CounterName that matches one CounterSet::AddCounter() call /// CounterData object with matched counterName - public CounterData this[string counterName!!] + public CounterData this[string counterName] { get { + if (counterName is null) + { + throw new ArgumentNullException(nameof(counterName)); + } + if (counterName.Length == 0) { throw new ArgumentNullException(nameof(counterName)); } + if (_disposed != 0) { return null; diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs index 7e4c4953f4d057..346d76d58af1d5 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs @@ -1325,8 +1325,11 @@ public static Process Start(string fileName, string arguments) [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] - public static Process Start(string fileName!!, IEnumerable arguments!!) + public static Process Start(string fileName, IEnumerable arguments) { + ArgumentNullException.ThrowIfNull(fileName); + ArgumentNullException.ThrowIfNull(arguments); + var startInfo = new ProcessStartInfo(fileName); foreach (string argument in arguments) { @@ -1347,8 +1350,10 @@ public static Process Start(string fileName!!, IEnumerable arguments!!) [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] - public static Process? Start(ProcessStartInfo startInfo!!) + public static Process? Start(ProcessStartInfo startInfo) { + ArgumentNullException.ThrowIfNull(startInfo); + Process process = new Process(); process.StartInfo = startInfo; return process.Start() ? diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs index 8a3f22ba096712..ed3a1646b74ab6 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs @@ -38,9 +38,11 @@ public TextWriterTraceListener(Stream stream) /// Initializes a new instance of the class with the /// specified name and using the stream as the recipient of the debugging and tracing output. /// - public TextWriterTraceListener(Stream stream!!, string? name) + public TextWriterTraceListener(Stream stream, string? name) : base(name) { + ArgumentNullException.ThrowIfNull(stream); + _writer = new StreamWriter(stream); } @@ -59,9 +61,11 @@ public TextWriterTraceListener(TextWriter writer) /// debugging /// output. /// - public TextWriterTraceListener(TextWriter writer!!, string? name) + public TextWriterTraceListener(TextWriter writer, string? name) : base(name) { + ArgumentNullException.ThrowIfNull(writer); + _writer = writer; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs index 4d1fd4db4be2f7..cdb64669b093ac 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs @@ -27,8 +27,10 @@ internal CorrelationManager() public Guid ActivityId { get { return _activityId.Value; } set { _activityId.Value = value; } } - public void StartLogicalOperation(object operationId!!) + public void StartLogicalOperation(object operationId) { + ArgumentNullException.ThrowIfNull(operationId); + _stackWrapper.Push(operationId); } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs index 1928a5a1ae81ed..6fa3a7193938d2 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs @@ -16,9 +16,11 @@ public SourceFilter(string source) Source = source; } - public override bool ShouldTrace(TraceEventCache? cache, string source!!, TraceEventType eventType, int id, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? formatOrMessage, + public override bool ShouldTrace(TraceEventCache? cache, string source, TraceEventType eventType, int id, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string? formatOrMessage, object?[]? args, object? data1, object?[]? data) { + ArgumentNullException.ThrowIfNull(source); + return string.Equals(_src, source); } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs index 3decbbb537b175..514d7df1317bb9 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs @@ -83,8 +83,10 @@ public int Add(TraceListener listener) /// /// [To be supplied.] /// - public void AddRange(TraceListener[] value!!) + public void AddRange(TraceListener[] value) { + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) { this.Add(value[i]); @@ -94,8 +96,10 @@ public void AddRange(TraceListener[] value!!) /// /// [To be supplied.] /// - public void AddRange(TraceListenerCollection value!!) + public void AddRange(TraceListenerCollection value) { + ArgumentNullException.ThrowIfNull(value); + int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { @@ -142,8 +146,10 @@ public IEnumerator GetEnumerator() return _list.GetEnumerator(); } - internal static void InitializeListener(TraceListener listener!!) + internal static void InitializeListener(TraceListener listener) { + ArgumentNullException.ThrowIfNull(listener); + listener.IndentSize = TraceInternal.IndentSize; listener.IndentLevel = TraceInternal.IndentLevel; } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs index 097704bd2d76a9..39c499e38e14f8 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs @@ -17,7 +17,6 @@ void ICollection.CopyTo(Array array, int index) { CheckDisposed(); - // Parameter validation if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs index c177f70c758f16..83cc70f73ba626 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/TrackedCollection.cs @@ -15,7 +15,6 @@ internal sealed class TrackedCollection : ICollection, ICollection, IEnume // void ICollection.CopyTo(Array array, int index) { - // Parameter validation if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs index a717a45e7bd03a..8ff1ecc1c34dfc 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs @@ -10,8 +10,10 @@ namespace System.DirectoryServices.Protocols { public static partial class BerConverter { - public static byte[] Encode(string format!!, params object[] value) + public static byte[] Encode(string format, params object[] value) { + ArgumentNullException.ThrowIfNull(format); + // no need to turn on invalid encoding detection as we just do string->byte[] conversion. UTF8Encoding utf8Encoder = new UTF8Encoding(); byte[] encodingResult = null; @@ -298,8 +300,10 @@ public static object[] Decode(string format, byte[] value) throw new BerConversionException(); } - internal static object[] TryDecode(string format!!, byte[] value, out bool decodeSucceeded) + internal static object[] TryDecode(string format, byte[] value, out bool decodeSucceeded) { + ArgumentNullException.ThrowIfNull(format); + Debug.WriteLine("Begin decoding"); UTF8Encoding utf8Encoder = new UTF8Encoding(false, true); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs index ea46a1b47ea971..e0000b99c104bb 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs @@ -33,14 +33,20 @@ public DirectoryAttribute(string name, Uri value) : this(name, (object)value) { } - internal DirectoryAttribute(string name!!, object value!!) : this() + internal DirectoryAttribute(string name, object value) : this() { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + Name = name; Add(value); } - public DirectoryAttribute(string name!!, params object[] values!!) : this() + public DirectoryAttribute(string name, params object[] values) : this() { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(values); + Name = name; for (int i = 0; i < values.Length; i++) @@ -154,8 +160,10 @@ public object this[int index] public int Add(Uri value) => Add((object)value); - internal int Add(object value!!) + internal int Add(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is string) && !(value is byte[]) && !(value is Uri)) { throw new ArgumentException(SR.ValidValueType, nameof(value)); @@ -164,8 +172,10 @@ internal int Add(object value!!) return List.Add(value); } - public void AddRange(object[] values!!) + public void AddRange(object[] values) { + ArgumentNullException.ThrowIfNull(values); + if (!(values is string[]) && !(values is byte[][]) && !(values is Uri[])) { throw new ArgumentException(SR.ValidValuesType, nameof(values)); @@ -194,15 +204,19 @@ public void AddRange(object[] values!!) public void Insert(int index, Uri value) => Insert(index, (object)value); - private void Insert(int index, object value!!) + private void Insert(int index, object value) { + ArgumentNullException.ThrowIfNull(value); + List.Insert(index, value); } public void Remove(object value) => List.Remove(value); - protected override void OnValidate(object value!!) + protected override void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is string) && !(value is byte[]) && !(value is Uri)) { throw new ArgumentException(SR.ValidValueType, nameof(value)); @@ -260,8 +274,10 @@ internal void Add(string name, DirectoryAttribute value) Dictionary.Add(name.ToLowerInvariant(), value); } - public bool Contains(string attributeName!!) + public bool Contains(string attributeName) { + ArgumentNullException.ThrowIfNull(attributeName); + object objectName = attributeName.ToLowerInvariant(); return Dictionary.Contains(objectName); } @@ -291,8 +307,10 @@ public int Add(DirectoryAttribute attribute) return List.Add(attribute); } - public void AddRange(DirectoryAttribute[] attributes!!) + public void AddRange(DirectoryAttribute[] attributes) { + ArgumentNullException.ThrowIfNull(attributes); + foreach (DirectoryAttribute attribute in attributes) { if (attribute == null) @@ -304,8 +322,10 @@ public void AddRange(DirectoryAttribute[] attributes!!) InnerList.AddRange(attributes); } - public void AddRange(DirectoryAttributeCollection attributeCollection!!) + public void AddRange(DirectoryAttributeCollection attributeCollection) { + ArgumentNullException.ThrowIfNull(attributeCollection); + int currentCount = attributeCollection.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { @@ -366,8 +386,10 @@ public int Add(DirectoryAttributeModification attribute) return List.Add(attribute); } - public void AddRange(DirectoryAttributeModification[] attributes!!) + public void AddRange(DirectoryAttributeModification[] attributes) { + ArgumentNullException.ThrowIfNull(attributes); + foreach (DirectoryAttributeModification attribute in attributes) { if (attribute == null) @@ -379,8 +401,10 @@ public void AddRange(DirectoryAttributeModification[] attributes!!) InnerList.AddRange(attributes); } - public void AddRange(DirectoryAttributeModificationCollection attributeCollection!!) + public void AddRange(DirectoryAttributeModificationCollection attributeCollection) { + ArgumentNullException.ThrowIfNull(attributeCollection); + int currentCount = attributeCollection.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs index 6592f09945136d..adeaa4a71f528f 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs @@ -91,8 +91,10 @@ public class DirectoryControl { internal byte[] _directoryControlValue; - public DirectoryControl(string type!!, byte[] value, bool isCritical, bool serverSide) + public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide) { + ArgumentNullException.ThrowIfNull(type); + Type = type; if (value != null) @@ -408,8 +410,10 @@ public class VerifyNameControl : DirectoryControl public VerifyNameControl() : base("1.2.840.113556.1.4.1338", null, true, true) { } - public VerifyNameControl(string serverName!!) : this() + public VerifyNameControl(string serverName) : this() { + ArgumentNullException.ThrowIfNull(serverName); + _serverName = serverName; } @@ -635,8 +639,10 @@ public byte[] Cookie public class SortRequestControl : DirectoryControl { private SortKey[] _keys = Array.Empty(); - public SortRequestControl(params SortKey[] sortKeys!!) : base("1.2.840.113556.1.4.473", null, true, true) + public SortRequestControl(params SortKey[] sortKeys) : base("1.2.840.113556.1.4.473", null, true, true) { + ArgumentNullException.ThrowIfNull(sortKeys); + for (int i = 0; i < sortKeys.Length; i++) { if (sortKeys[i] == null) @@ -1053,13 +1059,17 @@ public DirectoryControl this[int index] set => List[index] = value ?? throw new ArgumentNullException(nameof(value)); } - public int Add(DirectoryControl control!!) + public int Add(DirectoryControl control) { + ArgumentNullException.ThrowIfNull(control); + return List.Add(control); } - public void AddRange(DirectoryControl[] controls!!) + public void AddRange(DirectoryControl[] controls) { + ArgumentNullException.ThrowIfNull(controls); + foreach (DirectoryControl control in controls) { if (control == null) @@ -1071,8 +1081,10 @@ public void AddRange(DirectoryControl[] controls!!) InnerList.AddRange(controls); } - public void AddRange(DirectoryControlCollection controlCollection!!) + public void AddRange(DirectoryControlCollection controlCollection) { + ArgumentNullException.ThrowIfNull(controlCollection); + int currentCount = controlCollection.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { @@ -1086,15 +1098,19 @@ public void AddRange(DirectoryControlCollection controlCollection!!) public int IndexOf(DirectoryControl value) => List.IndexOf(value); - public void Insert(int index, DirectoryControl value!!) + public void Insert(int index, DirectoryControl value) { + ArgumentNullException.ThrowIfNull(value); + List.Insert(index, value); } public void Remove(DirectoryControl value) => List.Remove(value); - protected override void OnValidate(object value!!) + protected override void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is DirectoryControl)) { throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryControl)), nameof(value)); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs index 09891e43a74423..e6d2ffac0d323f 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryRequest.cs @@ -50,8 +50,10 @@ public AddRequest(string distinguishedName, params DirectoryAttribute[] attribut } } - public AddRequest(string distinguishedName, string objectClass!!) : this() + public AddRequest(string distinguishedName, string objectClass) : this() { + ArgumentNullException.ThrowIfNull(objectClass); + DistinguishedName = distinguishedName; var objClassAttr = new DirectoryAttribute() @@ -77,8 +79,10 @@ public ModifyRequest(string distinguishedName, params DirectoryAttributeModifica Modifications.AddRange(modifications); } - public ModifyRequest(string distinguishedName, DirectoryAttributeOperation operation, string attributeName!!, params object[] values) : this() + public ModifyRequest(string distinguishedName, DirectoryAttributeOperation operation, string attributeName, params object[] values) : this() { + ArgumentNullException.ThrowIfNull(attributeName); + DistinguishedName = distinguishedName; var mod = new DirectoryAttributeModification() { @@ -120,8 +124,10 @@ public CompareRequest(string distinguishedName, string attributeName, Uri value) CompareRequestHelper(distinguishedName, attributeName, value); } - public CompareRequest(string distinguishedName, DirectoryAttribute assertion!!) + public CompareRequest(string distinguishedName, DirectoryAttribute assertion) { + ArgumentNullException.ThrowIfNull(assertion); + if (assertion.Count != 1) { throw new ArgumentException(SR.WrongNumValuesCompare); @@ -130,8 +136,11 @@ public CompareRequest(string distinguishedName, DirectoryAttribute assertion!!) CompareRequestHelper(distinguishedName, assertion.Name, assertion[0]); } - private void CompareRequestHelper(string distinguishedName, string attributeName!!, object value!!) + private void CompareRequestHelper(string distinguishedName, string attributeName, object value) { + ArgumentNullException.ThrowIfNull(attributeName); + ArgumentNullException.ThrowIfNull(value); + DistinguishedName = distinguishedName; Assertion.Name = attributeName; Assertion.Add(value); diff --git a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs index 65280fe8b70450..6fbee4644860a9 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs @@ -35,8 +35,10 @@ public class EnumVariant private object _currentValue = s_noMoreValues; private readonly IEnumVariant _enumerator; - public EnumVariant(IEnumVariant en!!) + public EnumVariant(IEnumVariant en) { + ArgumentNullException.ThrowIfNull(en); + _enumerator = en; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs index 0d83c977793497..c7423df1c7611f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs @@ -25,8 +25,10 @@ internal ActiveDirectoryInterSiteTransport(DirectoryContext context, ActiveDirec _cachedEntry = entry; } - public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context!!, ActiveDirectoryTransportType transport) + public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context, ActiveDirectoryTransportType transport) { + ArgumentNullException.ThrowIfNull(context); + // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail if ((context.Name == null) && (!context.isRootDomain())) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs index 3cec6f767e647a..ddcf08bef1d9dc 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs @@ -55,8 +55,10 @@ public ActiveDirectorySchedule() #pragma warning restore 612, 618 } - public ActiveDirectorySchedule(ActiveDirectorySchedule schedule!!) : this() + public ActiveDirectorySchedule(ActiveDirectorySchedule schedule) : this() { + ArgumentNullException.ThrowIfNull(schedule); + bool[] tmpSchedule = schedule._scheduleArray; for (int i = 0; i < 672; i++) _scheduleArray[i] = tmpSchedule[i]; @@ -121,8 +123,10 @@ public void SetSchedule(DayOfWeek day, HourOfDay fromHour, MinuteOfHour fromMinu _scheduleArray[i] = true; } - public void SetSchedule(DayOfWeek[] days!!, HourOfDay fromHour, MinuteOfHour fromMinute, HourOfDay toHour, MinuteOfHour toMinute) + public void SetSchedule(DayOfWeek[] days, HourOfDay fromHour, MinuteOfHour fromMinute, HourOfDay toHour, MinuteOfHour toMinute) { + ArgumentNullException.ThrowIfNull(days); + for (int i = 0; i < days.Length; i++) { if (days[i] < DayOfWeek.Sunday || days[i] > DayOfWeek.Saturday) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs index fcea89f347cc17..01653432e7baad 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -84,8 +84,10 @@ protected override void Dispose(bool disposing) #endregion IDisposable #region public methods - public static ActiveDirectorySchema GetSchema(DirectoryContext context!!) + public static ActiveDirectorySchema GetSchema(DirectoryContext context) { + ArgumentNullException.ThrowIfNull(context); + // contexttype should be Forest, DirectoryServer or ConfigurationSet if ((context.ContextType != DirectoryContextType.Forest) && (context.ContextType != DirectoryContextType.ConfigurationSet) && diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs index 7e068ce0718d92..143151f5aabe31 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -46,8 +46,10 @@ public class ActiveDirectorySchemaClass : IDisposable private bool _defaultSDSddlFormInitialized; #region constructors - public ActiveDirectorySchemaClass(DirectoryContext context!!, string ldapDisplayName) + public ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayName) { + ArgumentNullException.ThrowIfNull(context); + if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); @@ -219,8 +221,10 @@ protected virtual void Dispose(bool disposing) #endregion IDisposable #region public methods - public static ActiveDirectorySchemaClass FindByName(DirectoryContext context!!, string ldapDisplayName) + public static ActiveDirectorySchemaClass FindByName(DirectoryContext context, string ldapDisplayName) { + ArgumentNullException.ThrowIfNull(context); + ActiveDirectorySchemaClass? schemaClass = null; if ((context.Name == null) && (!context.isRootDomain())) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs index fd49fb2a08e1d2..702261984f4e6c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -77,8 +77,10 @@ public ActiveDirectorySchemaClass this[int index] } } - public int Add(ActiveDirectorySchemaClass schemaClass!!) + public int Add(ActiveDirectorySchemaClass schemaClass) { + ArgumentNullException.ThrowIfNull(schemaClass); + if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -94,8 +96,10 @@ public int Add(ActiveDirectorySchemaClass schemaClass!!) } } - public void AddRange(ActiveDirectorySchemaClass[] schemaClasses!!) + public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) { + ArgumentNullException.ThrowIfNull(schemaClasses); + foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { if (schemaClass == null) @@ -110,8 +114,10 @@ public void AddRange(ActiveDirectorySchemaClass[] schemaClasses!!) } } - public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses!!) + public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) { + ArgumentNullException.ThrowIfNull(schemaClasses); + foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { if (schemaClass == null) @@ -127,8 +133,10 @@ public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses!!) } } - public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses!!) + public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) { + ArgumentNullException.ThrowIfNull(schemaClasses); + foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { if (schemaClass == null) @@ -144,8 +152,10 @@ public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses! } } - public void Remove(ActiveDirectorySchemaClass schemaClass!!) + public void Remove(ActiveDirectorySchemaClass schemaClass) { + ArgumentNullException.ThrowIfNull(schemaClass); + if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -163,8 +173,10 @@ public void Remove(ActiveDirectorySchemaClass schemaClass!!) throw new ArgumentException(SR.Format(SR.NotFoundInCollection, schemaClass), nameof(schemaClass)); } - public void Insert(int index, ActiveDirectorySchemaClass schemaClass!!) + public void Insert(int index, ActiveDirectorySchemaClass schemaClass) { + ArgumentNullException.ThrowIfNull(schemaClass); + if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -180,8 +192,10 @@ public void Insert(int index, ActiveDirectorySchemaClass schemaClass!!) } } - public bool Contains(ActiveDirectorySchemaClass schemaClass!!) + public bool Contains(ActiveDirectorySchemaClass schemaClass) { + ArgumentNullException.ThrowIfNull(schemaClass); + if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -204,8 +218,10 @@ public void CopyTo(ActiveDirectorySchemaClass[] schemaClasses, int index) List.CopyTo(schemaClasses, index); } - public int IndexOf(ActiveDirectorySchemaClass schemaClass!!) + public int IndexOf(ActiveDirectorySchemaClass schemaClass) { + ArgumentNullException.ThrowIfNull(schemaClass); + if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -316,8 +332,10 @@ protected override void OnSetComplete(int index, object oldValue, object newValu } } - protected override void OnValidate(object value!!) + protected override void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is ActiveDirectorySchemaClass)) { throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs index 8733223967c17b..cce6a59a4cd9cb 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs @@ -100,8 +100,10 @@ public class ActiveDirectorySchemaProperty : IDisposable /* ReplicaLink */ new Syntax("2.5.5.10", 127, s_replicaLinkOMObjectClass)}; #region constructors - public ActiveDirectorySchemaProperty(DirectoryContext context!!, string ldapDisplayName) + public ActiveDirectorySchemaProperty(DirectoryContext context, string ldapDisplayName) { + ArgumentNullException.ThrowIfNull(context); + if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); @@ -273,8 +275,10 @@ protected virtual void Dispose(bool disposing) #endregion IDisposable #region public methods - public static ActiveDirectorySchemaProperty FindByName(DirectoryContext context!!, string ldapDisplayName) + public static ActiveDirectorySchemaProperty FindByName(DirectoryContext context, string ldapDisplayName) { + ArgumentNullException.ThrowIfNull(context); + ActiveDirectorySchemaProperty? schemaProperty = null; if ((context.Name == null) && (!context.isRootDomain())) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs index ae86871b689622..a1a139d45bb1d3 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -75,8 +75,10 @@ public ActiveDirectorySchemaProperty this[int index] } } - public int Add(ActiveDirectorySchemaProperty schemaProperty!!) + public int Add(ActiveDirectorySchemaProperty schemaProperty) { + ArgumentNullException.ThrowIfNull(schemaProperty); + if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -92,8 +94,10 @@ public int Add(ActiveDirectorySchemaProperty schemaProperty!!) } } - public void AddRange(ActiveDirectorySchemaProperty[] properties!!) + public void AddRange(ActiveDirectorySchemaProperty[] properties) { + ArgumentNullException.ThrowIfNull(properties); + foreach (ActiveDirectorySchemaProperty property in properties) { if (property == null) @@ -108,8 +112,10 @@ public void AddRange(ActiveDirectorySchemaProperty[] properties!!) } } - public void AddRange(ActiveDirectorySchemaPropertyCollection properties!!) + public void AddRange(ActiveDirectorySchemaPropertyCollection properties) { + ArgumentNullException.ThrowIfNull(properties); + foreach (ActiveDirectorySchemaProperty property in properties) { if (property == null) @@ -126,8 +132,10 @@ public void AddRange(ActiveDirectorySchemaPropertyCollection properties!!) } } - public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties!!) + public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) { + ArgumentNullException.ThrowIfNull(properties); + foreach (ActiveDirectorySchemaProperty property in properties) { if (property == null) @@ -144,8 +152,10 @@ public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties! } } - public void Remove(ActiveDirectorySchemaProperty schemaProperty!!) + public void Remove(ActiveDirectorySchemaProperty schemaProperty) { + ArgumentNullException.ThrowIfNull(schemaProperty); + if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -163,8 +173,10 @@ public void Remove(ActiveDirectorySchemaProperty schemaProperty!!) throw new ArgumentException(SR.Format(SR.NotFoundInCollection, schemaProperty), nameof(schemaProperty)); } - public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty!!) + public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty) { + ArgumentNullException.ThrowIfNull(schemaProperty); + if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -180,8 +192,10 @@ public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty!!) } } - public bool Contains(ActiveDirectorySchemaProperty schemaProperty!!) + public bool Contains(ActiveDirectorySchemaProperty schemaProperty) { + ArgumentNullException.ThrowIfNull(schemaProperty); + if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -218,8 +232,10 @@ public void CopyTo(ActiveDirectorySchemaProperty[] properties, int index) List.CopyTo(properties, index); } - public int IndexOf(ActiveDirectorySchemaProperty schemaProperty!!) + public int IndexOf(ActiveDirectorySchemaProperty schemaProperty) { + ArgumentNullException.ThrowIfNull(schemaProperty); + if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -330,8 +346,10 @@ protected override void OnSetComplete(int index, object oldValue, object newValu } } - protected override void OnValidate(object value!!) + protected override void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is ActiveDirectorySchemaProperty)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs index bd835e03140b70..7c9913e6da9255 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -1102,8 +1102,10 @@ protected virtual void Dispose(bool disposing) _disposed = true; } - private static void ValidateArgument(DirectoryContext context!!, string siteName) + private static void ValidateArgument(DirectoryContext context, string siteName) { + ArgumentNullException.ThrowIfNull(context); + // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail if ((context.Name == null) && (!context.isRootDomain())) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs index 5ea1d759b66944..86e89777a193df 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs @@ -40,8 +40,10 @@ public ActiveDirectorySite this[int index] } } - public int Add(ActiveDirectorySite site!!) + public int Add(ActiveDirectorySite site) { + ArgumentNullException.ThrowIfNull(site); + if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -51,21 +53,27 @@ public int Add(ActiveDirectorySite site!!) throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, site), nameof(site)); } - public void AddRange(ActiveDirectorySite[] sites!!) + public void AddRange(ActiveDirectorySite[] sites) { + ArgumentNullException.ThrowIfNull(sites); + for (int i = 0; ((i) < (sites.Length)); i = ((i) + (1))) this.Add(sites[i]); } - public void AddRange(ActiveDirectorySiteCollection sites!!) + public void AddRange(ActiveDirectorySiteCollection sites) { + ArgumentNullException.ThrowIfNull(sites); + int count = sites.Count; for (int i = 0; i < count; i++) this.Add(sites[i]); } - public bool Contains(ActiveDirectorySite site!!) + public bool Contains(ActiveDirectorySite site) { + ArgumentNullException.ThrowIfNull(site); + if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -89,8 +97,10 @@ public void CopyTo(ActiveDirectorySite[] array, int index) List.CopyTo(array, index); } - public int IndexOf(ActiveDirectorySite site!!) + public int IndexOf(ActiveDirectorySite site) { + ArgumentNullException.ThrowIfNull(site); + if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -109,8 +119,10 @@ public int IndexOf(ActiveDirectorySite site!!) return -1; } - public void Insert(int index, ActiveDirectorySite site!!) + public void Insert(int index, ActiveDirectorySite site) { + ArgumentNullException.ThrowIfNull(site); + if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -120,8 +132,10 @@ public void Insert(int index, ActiveDirectorySite site!!) throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection, site), nameof(site)); } - public void Remove(ActiveDirectorySite site!!) + public void Remove(ActiveDirectorySite site) { + ArgumentNullException.ThrowIfNull(site); + if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -211,8 +225,10 @@ protected override void OnSetComplete(int index, object oldValue, object newValu } } - protected override void OnValidate(object value!!) + protected override void OnValidate(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!(value is ActiveDirectorySite)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs index 906672485951ba..b779a7d4a8d441 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs @@ -1522,6 +1522,7 @@ public void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode) public unsafe void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode, float tension) { + ArgumentNullException.ThrowIfNull(brush); ArgumentNullException.ThrowIfNull(points); fixed (PointF* p = points) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs index dceda4189f6e1f..bbe88baa8aa830 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs @@ -511,6 +511,8 @@ public void ResetTransform() /// public void MultiplyTransform(Matrix matrix, MatrixOrder order) { + ArgumentNullException.ThrowIfNull(matrix); + if (matrix.NativeMatrix == IntPtr.Zero) { // Disposed matrices should result in a no-op. diff --git a/src/libraries/System.Drawing.Common/tests/PenTests.cs b/src/libraries/System.Drawing.Common/tests/PenTests.cs index 1ee4a8dcdf8c2d..797cfefaef5acb 100644 --- a/src/libraries/System.Drawing.Common/tests/PenTests.cs +++ b/src/libraries/System.Drawing.Common/tests/PenTests.cs @@ -899,14 +899,15 @@ public void MultiplyTransform_Matrix_SetsTransformToExpected(Matrix originalTran } } + [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Null refs on .NET Framework")] [ConditionalFact(Helpers.IsDrawingSupported)] - public void MultiplyTransform_NullMatrix_ThrowsNullReferenceException() + public void MultiplyTransform_NullMatrix_ThrowsArgumentNullException() { using (var brush = new SolidBrush(Color.Red)) using (var pen = new Pen(brush)) { - Assert.Throws(() => pen.MultiplyTransform(null)); - Assert.Throws(() => pen.MultiplyTransform(null, MatrixOrder.Prepend)); + Assert.Throws(() => pen.MultiplyTransform(null)); + Assert.Throws(() => pen.MultiplyTransform(null, MatrixOrder.Prepend)); } } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs index 3c300f5e1fb041..6c8a9a016468ce 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Enumerated.cs @@ -30,8 +30,13 @@ public sealed partial class AsnWriter /// /// /// - public void WriteEnumeratedValue(Enum value!!, Asn1Tag? tag = null) + public void WriteEnumeratedValue(Enum value, Asn1Tag? tag = null) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + WriteEnumeratedValue(tag?.AsPrimitive() ?? Asn1Tag.Enumerated, value.GetType(), value); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs index 149f2dc8e26288..d0c60d5d2b310e 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.NamedBitList.cs @@ -32,8 +32,13 @@ public sealed partial class AsnWriter /// /// is . /// - public void WriteNamedBitList(Enum value!!, Asn1Tag? tag = null) + public void WriteNamedBitList(Enum value, Asn1Tag? tag = null) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + CheckUniversalTag(tag, UniversalTagNumber.BitString); WriteNamedBitList(tag, value.GetType(), value); @@ -86,8 +91,13 @@ public void WriteNamedBitList(TEnum value, Asn1Tag? tag = null) where TEn /// For example, the bit array { false, true, true } encodes as 0b0110_0000 with 5 /// unused bits. /// - public void WriteNamedBitList(BitArray value!!, Asn1Tag? tag = null) + public void WriteNamedBitList(BitArray value, Asn1Tag? tag = null) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + CheckUniversalTag(tag, UniversalTagNumber.BitString); WriteBitArray(value, tag); diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs index d458f988e839e8..c9e3f45e4b454e 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Oid.cs @@ -28,8 +28,13 @@ public sealed partial class AsnWriter /// /// is . /// - public void WriteObjectIdentifier(string oidValue!!, Asn1Tag? tag = null) + public void WriteObjectIdentifier(string oidValue, Asn1Tag? tag = null) { + if (oidValue is null) + { + throw new ArgumentNullException(nameof(oidValue)); + } + WriteObjectIdentifier(oidValue.AsSpan(), tag); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs index 032c3ffec5691a..1330e0c1c7fd52 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.Text.cs @@ -36,8 +36,13 @@ public sealed partial class AsnWriter /// . is not correct for /// the method. /// - public void WriteCharacterString(UniversalTagNumber encodingType, string value!!, Asn1Tag? tag = null) + public void WriteCharacterString(UniversalTagNumber encodingType, string value, Asn1Tag? tag = null) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + WriteCharacterString(encodingType, value.AsSpan(), tag); } diff --git a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs index de4dc8ef0fd248..34343adc4e0949 100644 --- a/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs +++ b/src/libraries/System.Formats.Asn1/src/System/Formats/Asn1/AsnWriter.cs @@ -223,8 +223,13 @@ public bool EncodedValueEquals(ReadOnlySpan other) /// A or has not been closed via /// or . /// - public bool EncodedValueEquals(AsnWriter other!!) + public bool EncodedValueEquals(AsnWriter other) { + if (other is null) + { + throw new ArgumentNullException(nameof(other)); + } + return EncodeAsSpan().SequenceEqual(other.EncodeAsSpan()); } @@ -378,8 +383,13 @@ private static int GetEncodedLengthSubsequentByteCount(int length) /// This writer's value is encoded in a manner that is not compatible with the /// ruleset for the destination writer. /// - public void CopyTo(AsnWriter destination!!) + public void CopyTo(AsnWriter destination) { + if (destination is null) + { + throw new ArgumentNullException(nameof(destination)); + } + try { destination.WriteEncodedValue(EncodeAsSpan()); diff --git a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs index 166efb3e36550e..426bfa2a8802e6 100644 --- a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs +++ b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.String.cs @@ -22,8 +22,13 @@ public partial class CborWriter /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode. - public void WriteByteString(byte[] value!!) + public void WriteByteString(byte[] value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + WriteByteString(value.AsSpan()); } @@ -101,8 +106,13 @@ public void WriteEndIndefiniteLengthByteString() /// The major type of the encoded value is not permitted in the parent data item. /// -or- /// The written data is not accepted under the current conformance mode. - public void WriteTextString(string value!!) + public void WriteTextString(string value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + WriteTextString(value.AsSpan()); } diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs index 375257f1f18fad..979d01175eedf9 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/BrotliStream.cs @@ -25,8 +25,10 @@ public BrotliStream(Stream stream, CompressionMode mode) : this(stream, mode, le /// The stream to compress. /// One of the enumeration values that indicates whether to compress or decompress the stream. /// to leave the stream open after the object is disposed; otherwise, . - public BrotliStream(Stream stream!!, CompressionMode mode, bool leaveOpen) + public BrotliStream(Stream stream, CompressionMode mode, bool leaveOpen) { + ArgumentNullException.ThrowIfNull(stream); + switch (mode) { case CompressionMode.Compress: diff --git a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.Extract.cs b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.Extract.cs index 6631352d278782..00fa93bf15929e 100644 --- a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.Extract.cs +++ b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.Extract.cs @@ -181,8 +181,10 @@ public static void ExtractToDirectory(string sourceArchiveFileName, string desti /// Note that Unicode encodings other than UTF-8 may not be currently used for the entryNameEncoding, /// otherwise an is thrown. /// - public static void ExtractToDirectory(string sourceArchiveFileName!!, string destinationDirectoryName, Encoding? entryNameEncoding, bool overwriteFiles) + public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, Encoding? entryNameEncoding, bool overwriteFiles) { + ArgumentNullException.ThrowIfNull(sourceArchiveFileName); + using (ZipArchive archive = Open(sourceArchiveFileName, ZipArchiveMode.Read, entryNameEncoding)) { archive.ExtractToDirectory(destinationDirectoryName, overwriteFiles); diff --git a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Create.cs b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Create.cs index 8e780cc7793a23..c909d818123009 100644 --- a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Create.cs +++ b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Create.cs @@ -77,9 +77,13 @@ public static ZipArchiveEntry CreateEntryFromFile(this ZipArchive destination, string sourceFileName, string entryName, CompressionLevel compressionLevel) => DoCreateEntryFromFile(destination, sourceFileName, entryName, compressionLevel); - internal static ZipArchiveEntry DoCreateEntryFromFile(this ZipArchive destination!!, - string sourceFileName!!, string entryName!!, CompressionLevel? compressionLevel) + internal static ZipArchiveEntry DoCreateEntryFromFile(this ZipArchive destination, + string sourceFileName, string entryName, CompressionLevel? compressionLevel) { + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(sourceFileName); + ArgumentNullException.ThrowIfNull(entryName); + // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation // as it is a pluggable component that completely encapsulates the meaning of compressionLevel. diff --git a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Extract.cs b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Extract.cs index ed01fa2689e982..addddb489fcfc6 100644 --- a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Extract.cs +++ b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchive.Extract.cs @@ -65,8 +65,11 @@ public static void ExtractToDirectory(this ZipArchive source, string destination /// The directory specified must not exist. The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory. /// True to indicate overwrite. - public static void ExtractToDirectory(this ZipArchive source!!, string destinationDirectoryName!!, bool overwriteFiles) + public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName, bool overwriteFiles) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(destinationDirectoryName); + foreach (ZipArchiveEntry entry in source.Entries) { entry.ExtractRelativeToDirectory(destinationDirectoryName, overwriteFiles); diff --git a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchiveEntry.Extract.cs b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchiveEntry.Extract.cs index f3cf37712c54ae..f9ad6fe1bedb40 100644 --- a/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchiveEntry.Extract.cs +++ b/src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFileExtensions.ZipArchiveEntry.Extract.cs @@ -60,8 +60,11 @@ public static void ExtractToFile(this ZipArchiveEntry source, string destination /// The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory. /// True to indicate overwrite. - public static void ExtractToFile(this ZipArchiveEntry source!!, string destinationFileName!!, bool overwrite) + public static void ExtractToFile(this ZipArchiveEntry source, string destinationFileName, bool overwrite) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(destinationFileName); + // Rely on FileStream's ctor for further checking destinationFileName parameter FileMode fMode = overwrite ? FileMode.Create : FileMode.CreateNew; @@ -88,8 +91,11 @@ public static void ExtractToFile(this ZipArchiveEntry source!!, string destinati internal static void ExtractRelativeToDirectory(this ZipArchiveEntry source, string destinationDirectoryName) => ExtractRelativeToDirectory(source, destinationDirectoryName, overwrite: false); - internal static void ExtractRelativeToDirectory(this ZipArchiveEntry source!!, string destinationDirectoryName!!, bool overwrite) + internal static void ExtractRelativeToDirectory(this ZipArchiveEntry source, string destinationDirectoryName, bool overwrite) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(destinationDirectoryName); + // Note that this will give us a good DirectoryInfo even if destinationDirectoryName exists: DirectoryInfo di = Directory.CreateDirectory(destinationDirectoryName); string destinationDirectoryFullPath = di.FullName; diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs index 949e1d7385d9e0..771857da88188a 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/DeflateManagedStream.cs @@ -20,8 +20,10 @@ internal sealed partial class DeflateManagedStream : Stream private int _asyncOperations; // A specific constructor to allow decompression of Deflate64 - internal DeflateManagedStream(Stream stream!!, ZipArchiveEntry.CompressionMethodValues method, long uncompressedSize = -1) + internal DeflateManagedStream(Stream stream, ZipArchiveEntry.CompressionMethodValues method, long uncompressedSize = -1) { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs index 858ba4fc84e5eb..70c4747679ca96 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs @@ -49,8 +49,10 @@ public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leav /// Internal constructor to check stream validity and call the correct initialization function depending on /// the value of the CompressionMode given. /// - internal DeflateStream(Stream stream!!, CompressionMode mode, bool leaveOpen, int windowBits, long uncompressedSize = -1) + internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int windowBits, long uncompressedSize = -1) { + ArgumentNullException.ThrowIfNull(stream); + switch (mode) { case CompressionMode.Decompress: @@ -75,8 +77,10 @@ internal DeflateStream(Stream stream!!, CompressionMode mode, bool leaveOpen, in /// /// Internal constructor to specify the compressionlevel as well as the windowbits /// - internal DeflateStream(Stream stream!!, CompressionLevel compressionLevel, bool leaveOpen, int windowBits) + internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowBits) { + ArgumentNullException.ThrowIfNull(stream); + InitializeDeflater(stream, leaveOpen, windowBits, compressionLevel); } @@ -931,7 +935,6 @@ public void CopyFromSourceToDestination() public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - // Validate inputs Debug.Assert(buffer != _arrayPoolBuffer); _deflateStream.EnsureNotDisposed(); if (count <= 0) @@ -980,7 +983,6 @@ private async ValueTask WriteAsyncCore(ReadOnlyMemory buffer, Cancellation public override void Write(byte[] buffer, int offset, int count) { - // Validate inputs Debug.Assert(buffer != _arrayPoolBuffer); _deflateStream.EnsureNotDisposed(); diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs index 3adf8a65702567..4c5fc2483296d1 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs @@ -117,8 +117,10 @@ public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(str /// otherwise an is thrown. /// /// If a Unicode encoding other than UTF-8 is specified for the entryNameEncoding. - public ZipArchive(Stream stream!!, ZipArchiveMode mode, bool leaveOpen, Encoding? entryNameEncoding) + public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding? entryNameEncoding) { + ArgumentNullException.ThrowIfNull(stream); + EntryNameAndCommentEncoding = entryNameEncoding; Stream? extraTempStream = null; @@ -338,8 +340,10 @@ public void Dispose() /// The Zip archive is corrupt and the entries cannot be retrieved. /// A path relative to the root of the archive, identifying the desired entry. /// A wrapper for the file entry in the archive. If no entry in the archive exists with the specified name, null will be returned. - public ZipArchiveEntry? GetEntry(string entryName!!) + public ZipArchiveEntry? GetEntry(string entryName) { + ArgumentNullException.ThrowIfNull(entryName); + if (_mode == ZipArchiveMode.Create) throw new NotSupportedException(SR.EntriesInCreateMode); @@ -386,8 +390,10 @@ private set } } - private ZipArchiveEntry DoCreateEntry(string entryName!!, CompressionLevel? compressionLevel) + private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compressionLevel) { + ArgumentNullException.ThrowIfNull(entryName); + if (string.IsNullOrEmpty(entryName)) throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName)); diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs index 8aabc90911c8df..fe1d620411b621 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/IO/FileSystemAclExtensions.cs @@ -10,34 +10,47 @@ namespace System.IO { public static partial class FileSystemAclExtensions { - public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo!!) + public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo) { + ArgumentNullException.ThrowIfNull(directoryInfo); + return new DirectorySecurity(directoryInfo.FullName, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo!!, AccessControlSections includeSections) + public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo, AccessControlSections includeSections) { + ArgumentNullException.ThrowIfNull(directoryInfo); + return new DirectorySecurity(directoryInfo.FullName, includeSections); } - public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity!!) + public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity) { + ArgumentNullException.ThrowIfNull(directorySecurity); + string fullPath = Path.GetFullPath(directoryInfo.FullName); directorySecurity.Persist(fullPath); } - public static FileSecurity GetAccessControl(this FileInfo fileInfo!!) + public static FileSecurity GetAccessControl(this FileInfo fileInfo) { + ArgumentNullException.ThrowIfNull(fileInfo); + return GetAccessControl(fileInfo, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static FileSecurity GetAccessControl(this FileInfo fileInfo!!, AccessControlSections includeSections) + public static FileSecurity GetAccessControl(this FileInfo fileInfo, AccessControlSections includeSections) { + ArgumentNullException.ThrowIfNull(fileInfo); + return new FileSecurity(fileInfo.FullName, includeSections); } - public static void SetAccessControl(this FileInfo fileInfo!!, FileSecurity fileSecurity!!) + public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSecurity) { + ArgumentNullException.ThrowIfNull(fileInfo); + ArgumentNullException.ThrowIfNull(fileSecurity); + string fullPath = Path.GetFullPath(fileInfo.FullName); // Appropriate security check should be done for us by FileSecurity. fileSecurity.Persist(fullPath); @@ -49,8 +62,10 @@ public static void SetAccessControl(this FileInfo fileInfo!!, FileSecurity fileS /// An object that represents the file for retrieving security descriptors from /// is . /// The file stream is closed. - public static FileSecurity GetAccessControl(this FileStream fileStream!!) + public static FileSecurity GetAccessControl(this FileStream fileStream) { + ArgumentNullException.ThrowIfNull(fileStream); + SafeFileHandle handle = fileStream.SafeFileHandle; if (handle.IsClosed) { @@ -67,8 +82,11 @@ public static FileSecurity GetAccessControl(this FileStream fileStream!!) /// An object that determines the access control and audit security for the file. /// or is . /// The file stream is closed. - public static void SetAccessControl(this FileStream fileStream!!, FileSecurity fileSecurity!!) + public static void SetAccessControl(this FileStream fileStream, FileSecurity fileSecurity) { + ArgumentNullException.ThrowIfNull(fileStream); + ArgumentNullException.ThrowIfNull(fileSecurity); + SafeFileHandle handle = fileStream.SafeFileHandle; if (handle.IsClosed) { @@ -85,8 +103,11 @@ public static void SetAccessControl(this FileStream fileStream!!, FileSecurity f /// Could not find a part of the path. /// Access to the path is denied. /// This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.DirectoryInfo.Create(System.Security.AccessControl.DirectorySecurity)` .NET Framework method. - public static void Create(this DirectoryInfo directoryInfo!!, DirectorySecurity directorySecurity!!) + public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity) { + ArgumentNullException.ThrowIfNull(directoryInfo); + ArgumentNullException.ThrowIfNull(directorySecurity); + FileSystem.CreateDirectory(directoryInfo.FullName, directorySecurity.GetSecurityDescriptorBinaryForm()); } @@ -110,8 +131,10 @@ public static void Create(this DirectoryInfo directoryInfo!!, DirectorySecurity /// An I/O error occurs. /// Access to the path is denied. /// This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.FileStream.#ctor(System.String,System.IO.FileMode,System.Security.AccessControl.FileSystemRights,System.IO.FileShare,System.Int32,System.IO.FileOptions,System.Security.AccessControl.FileSecurity)` .NET Framework constructor. - public static FileStream Create(this FileInfo fileInfo!!, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity? fileSecurity) + public static FileStream Create(this FileInfo fileInfo, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity? fileSecurity) { + ArgumentNullException.ThrowIfNull(fileInfo); + // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; @@ -177,8 +200,9 @@ public static FileStream Create(this FileInfo fileInfo!!, FileMode mode, FileSys /// Could not find a part of the path. /// Access to the path is denied. /// This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.Directory.CreateDirectory(System.String,System.Security.AccessControl.DirectorySecurity)` .NET Framework method. - public static DirectoryInfo CreateDirectory(this DirectorySecurity directorySecurity!!, string path) + public static DirectoryInfo CreateDirectory(this DirectorySecurity directorySecurity, string path) { + ArgumentNullException.ThrowIfNull(directorySecurity); ArgumentException.ThrowIfNullOrEmpty(path); DirectoryInfo dirInfo = new DirectoryInfo(path); diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs index a7edee77e2375c..a86b1b5384c758 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs @@ -17,9 +17,11 @@ protected DirectoryObjectSecurity() return; } - protected DirectoryObjectSecurity(CommonSecurityDescriptor securityDescriptor!!) + protected DirectoryObjectSecurity(CommonSecurityDescriptor securityDescriptor) : base(securityDescriptor) { + ArgumentNullException.ThrowIfNull(securityDescriptor); + } #region Private Methods @@ -516,8 +518,10 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi #region Public Methods - protected void AddAccessRule(ObjectAccessRule rule!!) + protected void AddAccessRule(ObjectAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -532,8 +536,10 @@ protected void AddAccessRule(ObjectAccessRule rule!!) return; } - protected void SetAccessRule(ObjectAccessRule rule!!) + protected void SetAccessRule(ObjectAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -546,8 +552,10 @@ protected void SetAccessRule(ObjectAccessRule rule!!) } } - protected void ResetAccessRule(ObjectAccessRule rule!!) + protected void ResetAccessRule(ObjectAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -560,8 +568,10 @@ protected void ResetAccessRule(ObjectAccessRule rule!!) } } - protected bool RemoveAccessRule(ObjectAccessRule rule!!) + protected bool RemoveAccessRule(ObjectAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -579,8 +589,10 @@ protected bool RemoveAccessRule(ObjectAccessRule rule!!) } } - protected void RemoveAccessRuleAll(ObjectAccessRule rule!!) + protected void RemoveAccessRuleAll(ObjectAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -598,8 +610,10 @@ protected void RemoveAccessRuleAll(ObjectAccessRule rule!!) } } - protected void RemoveAccessRuleSpecific(ObjectAccessRule rule!!) + protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + if (SecurityDescriptor == null) { return; @@ -617,8 +631,10 @@ protected void RemoveAccessRuleSpecific(ObjectAccessRule rule!!) } } - protected void AddAuditRule(ObjectAuditRule rule!!) + protected void AddAuditRule(ObjectAuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -631,8 +647,10 @@ protected void AddAuditRule(ObjectAuditRule rule!!) } } - protected void SetAuditRule(ObjectAuditRule rule!!) + protected void SetAuditRule(ObjectAuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -645,8 +663,10 @@ protected void SetAuditRule(ObjectAuditRule rule!!) } } - protected bool RemoveAuditRule(ObjectAuditRule rule!!) + protected bool RemoveAuditRule(ObjectAuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -659,8 +679,10 @@ protected bool RemoveAuditRule(ObjectAuditRule rule!!) } } - protected void RemoveAuditRuleAll(ObjectAuditRule rule!!) + protected void RemoveAuditRuleAll(ObjectAuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -673,8 +695,10 @@ protected void RemoveAuditRuleAll(ObjectAuditRule rule!!) } } - protected void RemoveAuditRuleSpecific(ObjectAuditRule rule!!) + protected void RemoveAuditRuleSpecific(ObjectAuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs index 50cf85d690b81d..ecebf92fbb936f 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs @@ -162,8 +162,10 @@ public void ResetAccessRule(FileSystemAccessRule rule) base.ResetAccessRule(rule); } - public bool RemoveAccessRule(FileSystemAccessRule rule!!) + public bool RemoveAccessRule(FileSystemAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit. // This is to avoid dangling synchronize bit @@ -203,8 +205,10 @@ public void RemoveAccessRuleAll(FileSystemAccessRule rule) base.RemoveAccessRuleAll(rule); } - public void RemoveAccessRuleSpecific(FileSystemAccessRule rule!!) + public void RemoveAccessRuleSpecific(FileSystemAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit // This is to avoid dangling synchronize bit diff --git a/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs b/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs index 975ffd5c5c6413..933b4b2de550c9 100644 --- a/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs +++ b/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.cs @@ -9,8 +9,10 @@ public sealed partial class DriveInfo : ISerializable { private readonly string _name; - public DriveInfo(string driveName!!) + public DriveInfo(string driveName) { + ArgumentNullException.ThrowIfNull(driveName); + _name = NormalizeDriveName(driveName); } diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs index b7cea76f28de7a..1015cfebda5fb2 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.cs @@ -370,8 +370,10 @@ protected override void Dispose(bool disposing) } } - private static void CheckPathValidity(string path!!) + private static void CheckPathValidity(string path) { + ArgumentNullException.ThrowIfNull(path); + // Early check for directory parameter so that an exception can be thrown as early as possible. if (path.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path)); diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs index 0d06fa01ee7206..b0ab8780cc1740 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc32.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; @@ -85,8 +85,13 @@ protected override void GetHashAndResetCore(Span destination) /// /// is . /// - public static byte[] Hash(byte[] source!!) + public static byte[] Hash(byte[] source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return Hash(new ReadOnlySpan(source)); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs index e50ed951a6959f..0cd3a446970699 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/Crc64.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers.Binary; @@ -83,8 +83,13 @@ protected override void GetHashAndResetCore(Span destination) /// /// is . /// - public static byte[] Hash(byte[] source!!) + public static byte[] Hash(byte[] source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return Hash(new ReadOnlySpan(source)); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs index e1e00a803283a2..b9cf541799229d 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs @@ -80,8 +80,13 @@ protected NonCryptographicHashAlgorithm(int hashLengthInBytes) /// /// is . /// - public void Append(byte[] source!!) + public void Append(byte[] source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + Append(new ReadOnlySpan(source)); } @@ -94,8 +99,13 @@ public void Append(byte[] source!!) /// is . /// /// - public void Append(Stream stream!!) + public void Append(Stream stream) { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + byte[] buffer = ArrayPool.Shared.Rent(4096); while (true) @@ -126,8 +136,13 @@ public void Append(Stream stream!!) /// /// is . /// - public Task AppendAsync(Stream stream!!, CancellationToken cancellationToken = default) + public Task AppendAsync(Stream stream, CancellationToken cancellationToken = default) { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + return AppendAsyncCore(stream, cancellationToken); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs index ca36eab898dd90..c4c7af69446804 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash32.cs @@ -130,8 +130,13 @@ protected override void GetCurrentHashCore(Span destination) /// /// is . /// - public static byte[] Hash(byte[] source!!) + public static byte[] Hash(byte[] source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return Hash(new ReadOnlySpan(source)); } @@ -144,8 +149,13 @@ public static byte[] Hash(byte[] source!!) /// /// is . /// - public static byte[] Hash(byte[] source!!, int seed) + public static byte[] Hash(byte[] source, int seed) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return Hash(new ReadOnlySpan(source), seed); } diff --git a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs index 18726a8437ad4b..45105525be5744 100644 --- a/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs +++ b/src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.cs @@ -130,8 +130,13 @@ protected override void GetCurrentHashCore(Span destination) /// /// is . /// - public static byte[] Hash(byte[] source!!) + public static byte[] Hash(byte[] source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return Hash(new ReadOnlySpan(source)); } @@ -144,8 +149,13 @@ public static byte[] Hash(byte[] source!!) /// /// is . /// - public static byte[] Hash(byte[] source!!, long seed) + public static byte[] Hash(byte[] source, long seed) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return Hash(new ReadOnlySpan(source), seed); } diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs index 48b9b6f8db8f96..d5baea62bc9ab8 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFile.cs @@ -116,8 +116,10 @@ public void Close() } } - public void DeleteFile(string file!!) + public void DeleteFile(string file) { + ArgumentNullException.ThrowIfNull(file); + EnsureStoreIsValid(); try @@ -131,22 +133,28 @@ public void DeleteFile(string file!!) } } - public bool FileExists(string path!!) + public bool FileExists(string path) { + ArgumentNullException.ThrowIfNull(path); + EnsureStoreIsValid(); return File.Exists(GetFullPath(path)); } - public bool DirectoryExists(string path!!) + public bool DirectoryExists(string path) { + ArgumentNullException.ThrowIfNull(path); + EnsureStoreIsValid(); return Directory.Exists(GetFullPath(path)); } - public void CreateDirectory(string dir!!) + public void CreateDirectory(string dir) { + ArgumentNullException.ThrowIfNull(dir); + EnsureStoreIsValid(); string isPath = GetFullPath(dir); // Prepend IS root @@ -178,8 +186,10 @@ public void CreateDirectory(string dir!!) } } - public void DeleteDirectory(string dir!!) + public void DeleteDirectory(string dir) { + ArgumentNullException.ThrowIfNull(dir); + EnsureStoreIsValid(); try @@ -199,8 +209,10 @@ public string[] GetFileNames() } // foo\abc*.txt will give all abc*.txt files in foo directory - public string[] GetFileNames(string searchPattern!!) + public string[] GetFileNames(string searchPattern) { + ArgumentNullException.ThrowIfNull(searchPattern); + EnsureStoreIsValid(); try @@ -221,8 +233,10 @@ public string[] GetDirectoryNames() } // foo\data* will give all directory names in foo directory that starts with data - public string[] GetDirectoryNames(string searchPattern!!) + public string[] GetDirectoryNames(string searchPattern) { + ArgumentNullException.ThrowIfNull(searchPattern); + EnsureStoreIsValid(); try diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs index cfa037eeb2a9a4..7133e760cf24d1 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs @@ -81,8 +81,10 @@ private struct InitialiationData } // If IsolatedStorageFile is null, then we default to using a file that is scoped by user, appdomain, and assembly. - private static InitialiationData InitializeFileStream(string path!!, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile? isf) + private static InitialiationData InitializeFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile? isf) { + ArgumentNullException.ThrowIfNull(path); + if ((path.Length == 0) || path.Equals(BackSlash)) throw new ArgumentException( SR.IsolatedStorage_Path); diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs index 1b9e7217e96463..7945d8e741ddf9 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs @@ -103,9 +103,11 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite); } - public static MemoryMappedFile CreateFromFile(string path!!, FileMode mode, string? mapName, long capacity, + public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string? mapName, long capacity, MemoryMappedFileAccess access) { + ArgumentNullException.ThrowIfNull(path); + if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); @@ -184,10 +186,12 @@ public static MemoryMappedFile CreateFromFile(string path!!, FileMode mode, stri return new MemoryMappedFile(handle, fileHandle, false); } - public static MemoryMappedFile CreateFromFile(FileStream fileStream!!, string? mapName, long capacity, + public static MemoryMappedFile CreateFromFile(FileStream fileStream, string? mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { + ArgumentNullException.ThrowIfNull(fileStream); + if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs index 362242c6896c10..91de323bf577b5 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs @@ -70,8 +70,13 @@ internal sealed class ContentType /// If the contentType string has leading or /// trailing Linear White Spaces(LWS) characters /// If the contentType string invalid CR-LF characters - internal ContentType(string contentType!!) + internal ContentType(string contentType) { + if (contentType is null) + { + throw new ArgumentNullException(nameof(contentType)); + } + if (contentType.Length == 0) { _contentType = string.Empty; diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/IgnoreFlushAndCloseStream.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/IgnoreFlushAndCloseStream.cs index 6901cb11751c3a..72e6076b68a96d 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/IgnoreFlushAndCloseStream.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/IgnoreFlushAndCloseStream.cs @@ -17,9 +17,9 @@ internal sealed class IgnoreFlushAndCloseStream : Stream /// Constructor /// /// - internal IgnoreFlushAndCloseStream(Stream stream!!) + internal IgnoreFlushAndCloseStream(Stream stream) { - _stream = stream; + _stream = stream ?? throw new ArgumentNullException(nameof(stream)); } #endregion Constructor diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs index a8913aae336ec6..c5f37735a85721 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs @@ -387,8 +387,17 @@ private static void ProcessEndElementForRelationshipTag(XmlCompatibilityReader r /// Null OK (ID will be generated). /// Indicates whether the add call is made while parsing existing relationships /// from a relationship part, or we are adding a new relationship - private PackageRelationship Add(Uri targetUri!!, TargetMode targetMode, string relationshipType!!, string? id, bool parsing) + private PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string? id, bool parsing) { + if (targetUri is null) + { + throw new ArgumentNullException(nameof(targetUri)); + } + if (relationshipType is null) + { + throw new ArgumentNullException(nameof(relationshipType)); + } + ThrowIfInvalidRelationshipType(relationshipType); //Verify if the Enum value is valid diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs index fabe42d73b09db..ad9cecbf0cda79 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs @@ -33,8 +33,13 @@ public static partial class PackUriHelper /// If partUri parameter ends with "/" /// If partUri parameter starts with two "/" /// If partUri parameter has a fragment - public static Uri CreatePartUri(Uri partUri!!) + public static Uri CreatePartUri(Uri partUri) { + if (partUri is null) + { + throw new ArgumentNullException(nameof(partUri)); + } + ThrowIfAbsoluteUri(partUri); string serializedPartUri = partUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.SafeUnescaped); @@ -71,8 +76,17 @@ public static Uri CreatePartUri(Uri partUri!!) /// If either sourcePartUri or targetUri parameter is null /// If either sourcePartUri or targetUri parameter is an absolute Uri /// If sourcePartUri parameter does not conform to the valid partUri syntax - public static Uri ResolvePartUri(Uri sourcePartUri!!, Uri targetUri!!) + public static Uri ResolvePartUri(Uri sourcePartUri, Uri targetUri) { + if (sourcePartUri is null) + { + throw new ArgumentNullException(nameof(sourcePartUri)); + } + if (targetUri is null) + { + throw new ArgumentNullException(nameof(targetUri)); + } + ThrowIfAbsoluteUri(sourcePartUri); ThrowIfAbsoluteUri(targetUri); @@ -94,8 +108,17 @@ public static Uri ResolvePartUri(Uri sourcePartUri!!, Uri targetUri!!) /// The relative path between two parts /// If either the sourcePartUri or targetPartUri parameter is null /// If either sourcePartUri or targetPartUri parameter does not conform to the valid partUri syntax - public static Uri GetRelativeUri(Uri sourcePartUri!!, Uri targetPartUri!!) + public static Uri GetRelativeUri(Uri sourcePartUri, Uri targetPartUri) { + if (sourcePartUri is null) + { + throw new ArgumentNullException(nameof(sourcePartUri)); + } + if (targetPartUri is null) + { + throw new ArgumentNullException(nameof(targetPartUri)); + } + sourcePartUri = new Uri(s_defaultUri, ValidatePartUri(sourcePartUri)); targetPartUri = new Uri(s_defaultUri, ValidatePartUri(targetPartUri)); @@ -109,8 +132,13 @@ public static Uri GetRelativeUri(Uri sourcePartUri!!, Uri targetPartUri!!) /// Normalized Part Uri /// If partUri is null /// If partUri parameter does not conform to the valid partUri syntax - public static Uri GetNormalizedPartUri(Uri partUri!!) + public static Uri GetNormalizedPartUri(Uri partUri) { + if (partUri is null) + { + throw new ArgumentNullException(nameof(partUri)); + } + if (!(partUri is ValidatedPartUri)) partUri = ValidatePartUri(partUri); return ((ValidatedPartUri)partUri).NormalizedPartUri; @@ -152,8 +180,13 @@ public static int ComparePartUri(Uri? firstPartUri, Uri? secondPartUri) /// If partUri parameter is null /// If partUri parameter is an absolute Uri /// If partUri parameter does not conform to the valid partUri Syntax - public static bool IsRelationshipPartUri(Uri partUri!!) + public static bool IsRelationshipPartUri(Uri partUri) { + if (partUri is null) + { + throw new ArgumentNullException(nameof(partUri)); + } + if (!(partUri is ValidatedPartUri)) partUri = ValidatePartUri(partUri); @@ -173,8 +206,13 @@ public static bool IsRelationshipPartUri(Uri partUri!!) /// If partUri parameter is null /// If partUri parameter is an absolute Uri /// If partUri parameter does not conform to the valid partUri Syntax - public static Uri GetRelationshipPartUri(Uri partUri!!) + public static Uri GetRelationshipPartUri(Uri partUri) { + if (partUri is null) + { + throw new ArgumentNullException(nameof(partUri)); + } + if (Uri.Compare(partUri, PackageRootUri, UriComponents.SerializationInfoString, UriFormat.UriEscaped, StringComparison.Ordinal) == 0) return PackageRelationship.ContainerRelationshipPartName; @@ -224,8 +262,13 @@ public static Uri GetRelationshipPartUri(Uri partUri!!) /// If relationshipPartUri parameter does not conform to the valid partUri Syntax /// If the relationshipPartUri is not a relationship part Uri itself /// If the resultant Uri obtained is a relationship part Uri - public static Uri GetSourcePartUriFromRelationshipPartUri(Uri relationshipPartUri!!) + public static Uri GetSourcePartUriFromRelationshipPartUri(Uri relationshipPartUri) { + if (relationshipPartUri is null) + { + throw new ArgumentNullException(nameof(relationshipPartUri)); + } + // Verify - // 1. Validates that this part Uri is a valid part Uri relationshipPartUri = ValidatePartUri(relationshipPartUri); @@ -352,8 +395,13 @@ internal static string GetStringForPartUri(Uri partUri) #endregion Internal Methods #region Private Methods - private static Exception? GetExceptionIfPartUriInvalid(Uri partUri!!, out string partUriString) + private static Exception? GetExceptionIfPartUriInvalid(Uri partUri, out string partUriString) { + if (partUri is null) + { + throw new ArgumentNullException(nameof(partUri)); + } + partUriString = string.Empty; Exception? argumentException = GetExceptionIfAbsoluteUri(partUri); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs index 82b10256af998d..d1d3f031a3b900 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs @@ -823,11 +823,16 @@ internal static void ThrowIfCompressionOptionInvalid(CompressionOption compressi /// If FileAccess enumeration [packageAccess] does not have one of the valid values /// If FileMode enumeration [packageMode] does not have one of the valid values public static Package Open( - string path!!, + string path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare) { + if (path is null) + { + throw new ArgumentNullException(nameof(path)); + } + ThrowIfFileModeInvalid(packageMode); ThrowIfFileAccessInvalid(packageAccess); @@ -885,8 +890,13 @@ public static Package Open( /// If FileAccess enumeration [packageAccess] does not have one of the valid values /// If package to be created should have readwrite/read access and underlying stream is write only /// If package to be created should have readwrite/write access and underlying stream is read only - public static Package Open(Stream stream!!, FileMode packageMode, FileAccess packageAccess) + public static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess) { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + Package? package = null; try { diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs index 3739ceb57ddadb..8558da81db4e59 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs @@ -93,11 +93,20 @@ protected PackagePart(Package package, Uri partUri, string? contentType) /// If parameter "partUri" is null /// If CompressionOption enumeration [compressionOption] does not have one of the valid values /// If parameter "partUri" does not conform to the valid partUri syntax - protected PackagePart(Package package!!, - Uri partUri!!, + protected PackagePart(Package package, + Uri partUri, string? contentType, CompressionOption compressionOption) { + if (package is null) + { + throw new ArgumentNullException(nameof(package)); + } + if (partUri is null) + { + throw new ArgumentNullException(nameof(partUri)); + } + Package.ThrowIfCompressionOptionInvalid(compressionOption); _uri = PackUriHelper.ValidatePartUri(partUri); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs index 36aa72cb50c5c5..38b28057ba08d0 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationship.cs @@ -110,8 +110,25 @@ public Package Package /// enum specifying the interpretation of the base uri for the target uri /// type name /// unique identifier - internal PackageRelationship(Package package!!, PackagePart? sourcePart, Uri targetUri!!, TargetMode targetMode, string relationshipType!!, string id!!) + internal PackageRelationship(Package package, PackagePart? sourcePart, Uri targetUri, TargetMode targetMode, string relationshipType, string id) { + if (package is null) + { + throw new ArgumentNullException(nameof(package)); + } + if (targetUri is null) + { + throw new ArgumentNullException(nameof(targetUri)); + } + if (relationshipType is null) + { + throw new ArgumentNullException(nameof(relationshipType)); + } + if (id is null) + { + throw new ArgumentNullException(nameof(id)); + } + //sourcePart can be null to represent that the relationships are at the package level // The ID is guaranteed to be an XML ID by the caller (InternalRelationshipCollection). diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs index 2ea435a5132ac3..678986d2af3b68 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackageRelationshipSelector.cs @@ -28,8 +28,17 @@ public sealed class PackageRelationshipSelector /// If PackageRelationshipSelectorType.Type and selection criteria is not valid relationship type /// If sourceUri is not "/" to indicate the PackageRoot, then it must conform to the /// valid PartUri syntax - public PackageRelationshipSelector(Uri sourceUri!!, PackageRelationshipSelectorType selectorType, string selectionCriteria!!) + public PackageRelationshipSelector(Uri sourceUri, PackageRelationshipSelectorType selectorType, string selectionCriteria) { + if (sourceUri is null) + { + throw new ArgumentNullException(nameof(sourceUri)); + } + if (selectionCriteria is null) + { + throw new ArgumentNullException(nameof(selectionCriteria)); + } + //If the sourceUri is not equal to "/", it must be a valid part name. if (Uri.Compare(sourceUri, PackUriHelper.PackageRootUri, UriComponents.SerializationInfoString, UriFormat.UriEscaped, StringComparison.Ordinal) != 0) sourceUri = PackUriHelper.ValidatePartUri(sourceUri); @@ -103,8 +112,13 @@ public string SelectionCriteria /// Package object from which we get the relationships /// /// If package parameter is null - public List Select(Package package!!) + public List Select(Package package) { + if (package is null) + { + throw new ArgumentNullException(nameof(package)); + } + List relationships = new List(0); switch (SelectorType) diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs index 6222a5b00c768a..a8426cb14cc53a 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReader.cs @@ -163,8 +163,13 @@ public static PipeReader Create(ReadOnlySequence sequence) /// The pipe writer to which the contents of the current stream will be copied. /// The token to monitor for cancellation requests. The default value is . /// A task that represents the asynchronous copy operation. - public virtual Task CopyToAsync(PipeWriter destination!!, CancellationToken cancellationToken = default) + public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default) { + if (destination is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination); + } + if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); @@ -180,8 +185,13 @@ public virtual Task CopyToAsync(PipeWriter destination!!, CancellationToken canc /// The stream to which the contents of the current stream will be copied. /// The token to monitor for cancellation requests. The default value is . /// A task that represents the asynchronous copy operation. - public virtual Task CopyToAsync(Stream destination!!, CancellationToken cancellationToken = default) + public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default) { + if (destination is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination); + } + if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs index c1d4635b10cdbc..bc8edbc6804762 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeReaderStream.cs @@ -45,8 +45,13 @@ public override void Flush() { } - public override int Read(byte[] buffer!!, int offset, int count) + public override int Read(byte[] buffer, int offset, int count) { + if (buffer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); + } + return ReadInternal(new Span(buffer, offset, count)); } @@ -75,8 +80,13 @@ public sealed override IAsyncResult BeginRead(byte[] buffer, int offset, int cou public sealed override int EndRead(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); - public override Task ReadAsync(byte[] buffer!!, int offset, int count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { + if (buffer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); + } + return ReadAsyncInternal(new Memory(buffer, offset, count), cancellationToken).AsTask(); } diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs index 9c5e19b05bbab9..dc9c34a6c2a839 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/PipeWriterStream.cs @@ -69,8 +69,13 @@ public sealed override void EndWrite(IAsyncResult asyncResult) => public override void Write(byte[] buffer, int offset, int count) => WriteAsync(buffer, offset, count).GetAwaiter().GetResult(); - public override Task WriteAsync(byte[] buffer!!, int offset, int count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { + if (buffer is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); + } + ValueTask valueTask = _pipeWriter.WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken); return GetFlushResultAsTask(valueTask); diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs index b9cecadcb9dba7..9ced0e1c94ce1e 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeExtensions.cs @@ -14,8 +14,17 @@ public static class StreamPipeExtensions /// The writer to which the contents of the source stream will be copied. /// The token to monitor for cancellation requests. The default value is . /// A task that represents the asynchronous copy operation. - public static Task CopyToAsync(this Stream source!!, PipeWriter destination!!, CancellationToken cancellationToken = default) + public static Task CopyToAsync(this Stream source, PipeWriter destination, CancellationToken cancellationToken = default) { + if (source is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); + } + if (destination is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination); + } + if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs index 288e7cb2fca019..9b101ce7ac2de2 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs @@ -35,8 +35,17 @@ internal sealed class StreamPipeReader : PipeReader /// /// The stream to read from. /// The options to use. - public StreamPipeReader(Stream readingStream!!, StreamPipeReaderOptions options!!) + public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options) { + if (readingStream is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.readingStream); + } + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options); + } + InnerStream = readingStream; _options = options; _bufferSegmentPool = new BufferSegmentStack(InitialSegmentPoolSize); diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs index bfd90adeefbc6a..59c14e4ecd2e02 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs @@ -46,8 +46,17 @@ private CancellationTokenSource InternalTokenSource } } - public StreamPipeWriter(Stream writingStream!!, StreamPipeWriterOptions options!!) + public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options) { + if (writingStream is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.writingStream); + } + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options); + } + InnerStream = writingStream; _minimumBufferSize = options.MinimumBufferSize; _pool = options.Pool == MemoryPool.Shared ? null : options.Pool; diff --git a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/ThrowHelper.cs b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/ThrowHelper.cs index 0fb31686d65d21..ec4faf30722778 100644 --- a/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/ThrowHelper.cs +++ b/src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/ThrowHelper.cs @@ -98,6 +98,11 @@ internal enum ExceptionArgument options, pauseWriterThreshold, resumeWriterThreshold, - sizeHint + sizeHint, + destination, + buffer, + source, + readingStream, + writingStream, } } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index 8fd4c3f1da15a0..043734aca630ee 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -87,9 +87,11 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d } // Create a NamedPipeClientStream from an existing server pipe handle. - public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle!!) + public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, 0) { + ArgumentNullException.ThrowIfNull(safePipeHandle); + if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(safePipeHandle)); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs index c9f46b24c54f90..bca963410f9103 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.cs @@ -138,9 +138,11 @@ private void ValidateParameters( } // Create a NamedPipeServerStream from an existing server pipe handle. - public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle!!) + public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, PipeTransmissionMode.Byte, 0) { + ArgumentNullException.ThrowIfNull(safePipeHandle); + if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(safePipeHandle)); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs index 8d0b188b622631..c59046acc4e2b8 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeSecurity.cs @@ -17,23 +17,31 @@ public PipeSecurity() internal PipeSecurity(SafePipeHandle safeHandle, AccessControlSections includeSections) : base(false, ResourceType.KernelObject, safeHandle, includeSections) { } - public void AddAccessRule(PipeAccessRule rule!!) + public void AddAccessRule(PipeAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + base.AddAccessRule(rule); } - public void SetAccessRule(PipeAccessRule rule!!) + public void SetAccessRule(PipeAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + base.SetAccessRule(rule); } - public void ResetAccessRule(PipeAccessRule rule!!) + public void ResetAccessRule(PipeAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + base.ResetAccessRule(rule); } - public bool RemoveAccessRule(PipeAccessRule rule!!) + public bool RemoveAccessRule(PipeAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit. AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); @@ -68,13 +76,13 @@ public bool RemoveAccessRule(PipeAccessRule rule!!) } } - public void RemoveAccessRuleSpecific(PipeAccessRule rule!!) + public void RemoveAccessRuleSpecific(PipeAccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit - AuthorizationRuleCollection rules = GetAccessRules(true, true, - rule.IdentityReference.GetType()); + AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs index 59bcc66559393f..61ed01e4bd6a7a 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipesAclExtensions.cs @@ -17,8 +17,10 @@ public static PipeSecurity GetAccessControl(this PipeStream stream) return new PipeSecurity(handle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity!!) + public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity) { + ArgumentNullException.ThrowIfNull(pipeSecurity); + // Checks that State != WaitingToConnect and State != Closed var handle = stream.SafePipeHandle; diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index 651410fb8396fe..c2beb7ef0d9932 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -568,9 +568,11 @@ private static int EndReadWrite(IAsyncResult asyncResult) } // this method is used by SerialPort upon SerialStream's creation - internal SerialStream(string portName!!, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, + internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) { + ArgumentNullException.ThrowIfNull(portName); + CheckBaudRate(baudRate); // Error checking done in SerialPort. diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs index 73587fd40f7048..b6f8a943d8115a 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs @@ -555,9 +555,11 @@ internal int BytesToWrite // -----------SECTION: constructor --------------------------* // this method is used by SerialPort upon SerialStream's creation - internal SerialStream(string portName!!, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, + internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) { + ArgumentNullException.ThrowIfNull(portName); + if (!portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || !uint.TryParse( #if NETCOREAPP diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs index 2a33673b59a056..298510f8a961f8 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs @@ -88,8 +88,10 @@ public override void Write(byte[] array, int offset, int count) Dispose(false); } - private static void CheckArrayArguments(byte[] array!!, int offset, int count) + private static void CheckArrayArguments(byte[] array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); if (count < 0) diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/BinaryOperationBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/BinaryOperationBinder.cs index dfbf5586382fe5..475a277183f974 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/BinaryOperationBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/BinaryOperationBinder.cs @@ -59,12 +59,12 @@ public DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, Dynam /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.RequiresNotNull(args, nameof(args)); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(args); ContractUtils.Requires(args.Length == 1, nameof(args)); var arg0 = args[0]; - ContractUtils.RequiresNotNull(arg0, nameof(args)); + ArgumentNullException.ThrowIfNull(arg0, nameof(args)); return target.BindBinaryOperation(this, arg0); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs index a9b0143babea87..46639f6313cb73 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/BindingRestrictions.cs @@ -40,7 +40,7 @@ private BindingRestrictions() /// The new set of binding restrictions. public BindingRestrictions Merge(BindingRestrictions restrictions) { - ContractUtils.RequiresNotNull(restrictions, nameof(restrictions)); + ArgumentNullException.ThrowIfNull(restrictions); if (this == Empty) { return restrictions; @@ -62,8 +62,8 @@ public BindingRestrictions Merge(BindingRestrictions restrictions) /// The new binding restrictions. public static BindingRestrictions GetTypeRestriction(Expression expression, Type type) { - ContractUtils.RequiresNotNull(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(type); return new TypeRestriction(expression, type); } @@ -93,7 +93,7 @@ internal static BindingRestrictions GetTypeRestriction(DynamicMetaObject obj) /// The new binding restrictions. public static BindingRestrictions GetInstanceRestriction(Expression expression, object? instance) { - ContractUtils.RequiresNotNull(expression, nameof(expression)); + ArgumentNullException.ThrowIfNull(expression); return new InstanceRestriction(expression, instance); } @@ -109,7 +109,7 @@ public static BindingRestrictions GetInstanceRestriction(Expression expression, /// public static BindingRestrictions GetExpressionRestriction(Expression expression) { - ContractUtils.RequiresNotNull(expression, nameof(expression)); + ArgumentNullException.ThrowIfNull(expression); ContractUtils.Requires(expression.Type == typeof(bool), nameof(expression)); return new CustomRestriction(expression); } @@ -344,7 +344,7 @@ private sealed class BindingRestrictionsProxy public BindingRestrictionsProxy(BindingRestrictions node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/CallInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/CallInfo.cs index 32948a983cf5c6..af1060f27480d6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/CallInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/CallInfo.cs @@ -48,7 +48,7 @@ public CallInfo(int argCount, params string[] argNames) /// The new instance. public CallInfo(int argCount, IEnumerable argNames) { - ContractUtils.RequiresNotNull(argNames, nameof(argNames)); + ArgumentNullException.ThrowIfNull(argNames); var argNameCol = argNames.ToReadOnly(); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs index ec1d4b89ef4f48..adf252cd6fe21b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ConvertBinder.cs @@ -17,7 +17,7 @@ public abstract class ConvertBinder : DynamicMetaObjectBinder /// true if the conversion should consider explicit conversions; otherwise, false. protected ConvertBinder(Type type, bool @explicit) { - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); Type = type; Explicit = @explicit; @@ -59,7 +59,7 @@ public DynamicMetaObject FallbackConvert(DynamicMetaObject target) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[]? args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); return target.BindConvert(this); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/CreateInstanceBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/CreateInstanceBinder.cs index 6b407f0404ec69..0039c5845385d6 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/CreateInstanceBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/CreateInstanceBinder.cs @@ -16,7 +16,7 @@ public abstract class CreateInstanceBinder : DynamicMetaObjectBinder /// The signature of the arguments at the call site. protected CreateInstanceBinder(CallInfo callInfo) { - ContractUtils.RequiresNotNull(callInfo, nameof(callInfo)); + ArgumentNullException.ThrowIfNull(callInfo); CallInfo = callInfo; } @@ -58,7 +58,7 @@ public DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, Dynami /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.RequiresNotNullItems(args, nameof(args)); return target.BindCreateInstance(this, args); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteIndexBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteIndexBinder.cs index ee2f307704d30e..02b0e5ec1056bf 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteIndexBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteIndexBinder.cs @@ -16,7 +16,7 @@ public abstract class DeleteIndexBinder : DynamicMetaObjectBinder /// The signature of the arguments at the call site. protected DeleteIndexBinder(CallInfo callInfo) { - ContractUtils.RequiresNotNull(callInfo, nameof(callInfo)); + ArgumentNullException.ThrowIfNull(callInfo); CallInfo = callInfo; } @@ -38,7 +38,7 @@ protected DeleteIndexBinder(CallInfo callInfo) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.RequiresNotNullItems(args, nameof(args)); return target.BindDeleteIndex(this, args); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs index 4215864b85b7f9..263073a63ae8b3 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DeleteMemberBinder.cs @@ -17,7 +17,7 @@ public abstract class DeleteMemberBinder : DynamicMetaObjectBinder /// true if the name should be matched ignoring case; false otherwise. protected DeleteMemberBinder(string name, bool ignoreCase) { - ContractUtils.RequiresNotNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name); Name = name; IgnoreCase = ignoreCase; @@ -64,7 +64,7 @@ public DynamicMetaObject FallbackDeleteMember(DynamicMetaObject target) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[]? args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); return target.BindDeleteMember(this); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs index 1a7a115cd94981..191f1b7ff7c9a1 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObject.cs @@ -25,8 +25,8 @@ public class DynamicMetaObject /// The set of binding restrictions under which the binding is valid. public DynamicMetaObject(Expression expression, BindingRestrictions restrictions) { - ContractUtils.RequiresNotNull(expression, nameof(expression)); - ContractUtils.RequiresNotNull(restrictions, nameof(restrictions)); + ArgumentNullException.ThrowIfNull(expression); + ArgumentNullException.ThrowIfNull(restrictions); Expression = expression; Restrictions = restrictions; @@ -106,7 +106,7 @@ public Type? RuntimeType /// The new representing the result of the binding. public virtual DynamicMetaObject BindConvert(ConvertBinder binder) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackConvert(this); } @@ -117,7 +117,7 @@ public virtual DynamicMetaObject BindConvert(ConvertBinder binder) /// The new representing the result of the binding. public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackGetMember(this); } @@ -129,7 +129,7 @@ public virtual DynamicMetaObject BindGetMember(GetMemberBinder binder) /// The new representing the result of the binding. public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackSetMember(this, value); } @@ -140,7 +140,7 @@ public virtual DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMe /// The new representing the result of the binding. public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackDeleteMember(this); } @@ -152,7 +152,7 @@ public virtual DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) /// The new representing the result of the binding. public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackGetIndex(this, indexes); } @@ -165,7 +165,7 @@ public virtual DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMeta /// The new representing the result of the binding. public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackSetIndex(this, indexes, value); } @@ -177,7 +177,7 @@ public virtual DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMeta /// The new representing the result of the binding. public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackDeleteIndex(this, indexes); } @@ -189,7 +189,7 @@ public virtual DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, Dynam /// The new representing the result of the binding. public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackInvokeMember(this, args); } @@ -201,7 +201,7 @@ public virtual DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dyn /// The new representing the result of the binding. public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackInvoke(this, args); } @@ -213,7 +213,7 @@ public virtual DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObje /// The new representing the result of the binding. public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackCreateInstance(this, args); } @@ -224,7 +224,7 @@ public virtual DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, /// The new representing the result of the binding. public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackUnaryOperation(this); } @@ -236,7 +236,7 @@ public virtual DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) /// The new representing the result of the binding. public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return binder.FallbackBinaryOperation(this, arg); } @@ -253,13 +253,13 @@ public virtual DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binde /// The array of expressions. internal static Expression[] GetExpressions(DynamicMetaObject[] objects) { - ContractUtils.RequiresNotNull(objects, nameof(objects)); + ArgumentNullException.ThrowIfNull(objects); Expression[] res = new Expression[objects.Length]; for (int i = 0; i < objects.Length; i++) { DynamicMetaObject mo = objects[i]; - ContractUtils.RequiresNotNull(mo, nameof(objects)); + ArgumentNullException.ThrowIfNull(mo, nameof(objects)); Expression expr = mo.Expression; Debug.Assert(expr != null, "Unexpected null expression; ctor should have caught this."); res[i] = expr; @@ -280,7 +280,7 @@ internal static Expression[] GetExpressions(DynamicMetaObject[] objects) /// public static DynamicMetaObject Create(object value, Expression expression) { - ContractUtils.RequiresNotNull(expression, nameof(expression)); + ArgumentNullException.ThrowIfNull(expression); if (value is IDynamicMetaObjectProvider ido) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs index 824c7845515e1f..96157d4f793c51 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/DynamicMetaObjectBinder.cs @@ -47,9 +47,9 @@ protected DynamicMetaObjectBinder() /// public sealed override Expression Bind(object[] args, ReadOnlyCollection parameters, LabelTarget returnLabel) { - ContractUtils.RequiresNotNull(args, nameof(args)); - ContractUtils.RequiresNotNull(parameters, nameof(parameters)); - ContractUtils.RequiresNotNull(returnLabel, nameof(returnLabel)); + ArgumentNullException.ThrowIfNull(args); + ArgumentNullException.ThrowIfNull(parameters); + ArgumentNullException.ThrowIfNull(returnLabel); if (args.Length == 0) { throw System.Linq.Expressions.Error.OutOfRange("args.Length", 1); @@ -188,7 +188,7 @@ public Expression GetUpdateExpression(Type type) /// The representing the result of the binding. public DynamicMetaObject Defer(DynamicMetaObject target, params DynamicMetaObject[]? args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); if (args == null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs index 78c8bdd9188cad..46905a8a0b1f91 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/ExpandoObject.cs @@ -300,7 +300,7 @@ DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) #region Helper methods private void TryAddMember(string key, object? value) { - ContractUtils.RequiresNotNull(key, nameof(key)); + ArgumentNullException.ThrowIfNull(key); // Pass null to the class, which forces lookup. TrySetValue(null, -1, value, key, ignoreCase: false, add: true); } @@ -328,7 +328,7 @@ private sealed class KeyCollectionDebugView public KeyCollectionDebugView(ICollection collection) { - ContractUtils.RequiresNotNull(collection, nameof(collection)); + ArgumentNullException.ThrowIfNull(collection); _collection = collection; } @@ -396,7 +396,7 @@ public bool Contains(string item) public void CopyTo(string[] array, int arrayIndex) { - ContractUtils.RequiresNotNull(array, nameof(array)); + ArgumentNullException.ThrowIfNull(array); ContractUtils.RequiresArrayRange(array, arrayIndex, _expandoCount, nameof(arrayIndex), nameof(Count)); lock (_expando.LockObject) { @@ -467,7 +467,7 @@ private sealed class ValueCollectionDebugView public ValueCollectionDebugView(ICollection collection) { - ContractUtils.RequiresNotNull(collection, nameof(collection)); + ArgumentNullException.ThrowIfNull(collection); _collection = collection; } @@ -546,7 +546,7 @@ public bool Contains(object? item) public void CopyTo(object?[] array, int arrayIndex) { - ContractUtils.RequiresNotNull(array, nameof(array)); + ArgumentNullException.ThrowIfNull(array); ContractUtils.RequiresArrayRange(array, arrayIndex, _expandoCount, nameof(arrayIndex), nameof(Count)); lock (_expando.LockObject) { @@ -630,7 +630,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() } set { - ContractUtils.RequiresNotNull(key, nameof(key)); + ArgumentNullException.ThrowIfNull(key); // Pass null to the class, which forces lookup. TrySetValue(null, -1, value, key, ignoreCase: false, add: false); } @@ -643,7 +643,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() bool IDictionary.ContainsKey(string key) { - ContractUtils.RequiresNotNull(key, nameof(key)); + ArgumentNullException.ThrowIfNull(key); ExpandoData data = _data; int index = data.Class.GetValueIndexCaseSensitive(key); @@ -652,7 +652,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() bool IDictionary.Remove(string key) { - ContractUtils.RequiresNotNull(key, nameof(key)); + ArgumentNullException.ThrowIfNull(key); // Pass null to the class, which forces lookup. return TryDeleteValue(null, -1, key, ignoreCase: false, deleteValue: Uninitialized); } @@ -712,7 +712,7 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { - ContractUtils.RequiresNotNull(array, nameof(array)); + ArgumentNullException.ThrowIfNull(array); // We want this to be atomic and not throw, though we must do the range checks inside this lock. lock (LockObject) @@ -825,7 +825,7 @@ private DynamicMetaObject BindGetOrInvokeMember(DynamicMetaObjectBinder binder, public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return BindGetOrInvokeMember( binder, binder.Name, @@ -837,7 +837,7 @@ public override DynamicMetaObject BindGetMember(GetMemberBinder binder) public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return BindGetOrInvokeMember( binder, binder.Name, @@ -849,8 +849,8 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); - ContractUtils.RequiresNotNull(value, nameof(value)); + ArgumentNullException.ThrowIfNull(binder); + ArgumentNullException.ThrowIfNull(value); ExpandoClass klass; int index; @@ -878,7 +878,7 @@ public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicM public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); int index = Value.Class.GetValueIndex(binder.Name, binder.IgnoreCase, Value); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetIndexBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetIndexBinder.cs index 4927adac166a60..33137b9e2d1f3d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetIndexBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetIndexBinder.cs @@ -16,7 +16,7 @@ public abstract class GetIndexBinder : DynamicMetaObjectBinder /// The signature of the arguments at the call site. protected GetIndexBinder(CallInfo callInfo) { - ContractUtils.RequiresNotNull(callInfo, nameof(callInfo)); + ArgumentNullException.ThrowIfNull(callInfo); CallInfo = callInfo; } @@ -38,7 +38,7 @@ protected GetIndexBinder(CallInfo callInfo) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.RequiresNotNullItems(args, nameof(args)); return target.BindGetIndex(this, args); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs index 420f5919975415..dd8773e892acd5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/GetMemberBinder.cs @@ -17,7 +17,7 @@ public abstract class GetMemberBinder : DynamicMetaObjectBinder /// true if the name should be matched ignoring case; false otherwise. protected GetMemberBinder(string name, bool ignoreCase) { - ContractUtils.RequiresNotNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name); Name = name; IgnoreCase = ignoreCase; @@ -64,7 +64,7 @@ public DynamicMetaObject FallbackGetMember(DynamicMetaObject target) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, params DynamicMetaObject[]? args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); return target.BindGetMember(this); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeBinder.cs index e503bbea0e587a..f02cc2802b0e21 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeBinder.cs @@ -16,7 +16,7 @@ public abstract class InvokeBinder : DynamicMetaObjectBinder /// The signature of the arguments at the call site. protected InvokeBinder(CallInfo callInfo) { - ContractUtils.RequiresNotNull(callInfo, nameof(callInfo)); + ArgumentNullException.ThrowIfNull(callInfo); CallInfo = callInfo; } @@ -58,7 +58,7 @@ public DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObj /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.RequiresNotNullItems(args, nameof(args)); return target.BindInvoke(this, args); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeMemberBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeMemberBinder.cs index d320fdcd3e794d..ccd26068cd9d0f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeMemberBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/InvokeMemberBinder.cs @@ -18,8 +18,8 @@ public abstract class InvokeMemberBinder : DynamicMetaObjectBinder /// The signature of the arguments at the call site. protected InvokeMemberBinder(string name, bool ignoreCase, CallInfo callInfo) { - ContractUtils.RequiresNotNull(name, nameof(name)); - ContractUtils.RequiresNotNull(callInfo, nameof(callInfo)); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(callInfo); Name = name; IgnoreCase = ignoreCase; @@ -54,7 +54,7 @@ protected InvokeMemberBinder(string name, bool ignoreCase, CallInfo callInfo) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.RequiresNotNullItems(args, nameof(args)); return target.BindInvokeMember(this, args); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetIndexBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetIndexBinder.cs index 9436eb1deb9005..1d75795f39ab34 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetIndexBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetIndexBinder.cs @@ -16,7 +16,7 @@ public abstract class SetIndexBinder : DynamicMetaObjectBinder /// The signature of the arguments at the call site. protected SetIndexBinder(CallInfo callInfo) { - ContractUtils.RequiresNotNull(callInfo, nameof(callInfo)); + ArgumentNullException.ThrowIfNull(callInfo); CallInfo = callInfo; } @@ -38,14 +38,14 @@ protected SetIndexBinder(CallInfo callInfo) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.RequiresNotNull(args, nameof(args)); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(args); ContractUtils.Requires(args.Length >= 2, nameof(args)); DynamicMetaObject value = args[args.Length - 1]; DynamicMetaObject[] indexes = args.RemoveLast(); - ContractUtils.RequiresNotNull(value, nameof(args)); + ArgumentNullException.ThrowIfNull(value, nameof(args)); ContractUtils.RequiresNotNullItems(indexes, nameof(args)); return target.BindSetIndex(this, indexes, value); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetMemberBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetMemberBinder.cs index 168109bc71da61..10089c45b9b401 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetMemberBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/SetMemberBinder.cs @@ -17,7 +17,7 @@ public abstract class SetMemberBinder : DynamicMetaObjectBinder /// true if the name should be matched ignoring case; false otherwise. protected SetMemberBinder(string name, bool ignoreCase) { - ContractUtils.RequiresNotNull(name, nameof(name)); + ArgumentNullException.ThrowIfNull(name); Name = name; IgnoreCase = ignoreCase; @@ -46,12 +46,12 @@ protected SetMemberBinder(string name, bool ignoreCase) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[] args) { - ContractUtils.RequiresNotNull(target, nameof(target)); - ContractUtils.RequiresNotNull(args, nameof(args)); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(args); ContractUtils.Requires(args.Length == 1, nameof(args)); var arg0 = args[0]; - ContractUtils.RequiresNotNull(arg0, nameof(args)); + ArgumentNullException.ThrowIfNull(arg0, nameof(args)); return target.BindSetMember(this, arg0); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs index 9eddf145c28798..797eefd3295193 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/UnaryOperationBinder.cs @@ -70,7 +70,7 @@ public DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target) /// The representing the result of the binding. public sealed override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObject[]? args) { - ContractUtils.RequiresNotNull(target, nameof(target)); + ArgumentNullException.ThrowIfNull(target); ContractUtils.Requires(args == null || args.Length == 0, nameof(args)); return target.BindUnaryOperation(this); diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs index e481185ffa57a9..d0288f7736342f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ContractUtils.cs @@ -46,28 +46,6 @@ public static void Requires([DoesNotReturnIf(false)] bool precondition, string p } } - /// - /// Requires the to be non-null. - /// - /// - /// The value to check for being non-null. - /// - /// - /// The parameter name to use in the property when an exception is thrown. - /// - /// - /// Thrown if is null. - /// - public static void RequiresNotNull(object value, string paramName) - { - Debug.Assert(!string.IsNullOrEmpty(paramName)); - - if (value == null) - { - throw new ArgumentNullException(paramName); - } - } - /// /// Requires the to be non-null. /// @@ -108,7 +86,7 @@ public static void RequiresNotNull(object value, string paramName, int index) /// public static void RequiresNotEmpty(ICollection collection, string paramName) { - RequiresNotNull(collection, paramName); + ArgumentNullException.ThrowIfNull(collection, paramName); if (collection.Count == 0) { throw Error.NonEmptyCollectionRequired(paramName); @@ -130,7 +108,7 @@ public static void RequiresNotEmpty(ICollection collection, string paramNa public static void RequiresNotNullItems(IList array, string arrayName) { Debug.Assert(!string.IsNullOrEmpty(arrayName)); - RequiresNotNull(array, arrayName); + ArgumentNullException.ThrowIfNull(array, arrayName); for (int i = 0, n = array.Count; i < n; i++) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ListArgumentProvider.cs b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ListArgumentProvider.cs index bf9a528979edf6..c8b2784b39c041 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ListArgumentProvider.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Dynamic/Utils/ListArgumentProvider.cs @@ -87,7 +87,7 @@ public void Clear() public void CopyTo(T[] array, int index) { - ContractUtils.RequiresNotNull(array, nameof(array)); + ArgumentNullException.ThrowIfNull(array); if (index < 0) { throw LinqError.ArgumentOutOfRange(nameof(index)); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs index 4d6b22ec6fe734..d997789f0a4510 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/BlockExpression.cs @@ -760,7 +760,7 @@ public bool Contains(Expression item) public void CopyTo(Expression[] array, int index) { - ContractUtils.RequiresNotNull(array, nameof(array)); + ArgumentNullException.ThrowIfNull(array); if (index < 0) { throw Error.ArgumentOutOfRange(nameof(index)); @@ -900,7 +900,7 @@ public static BlockExpression Block(Expression arg0, Expression arg1, Expression /// The created . public static BlockExpression Block(params Expression[] expressions) { - ContractUtils.RequiresNotNull(expressions, nameof(expressions)); + ArgumentNullException.ThrowIfNull(expressions); RequiresCanRead(expressions, nameof(expressions)); return GetOptimizedBlockExpression(expressions); @@ -924,7 +924,7 @@ public static BlockExpression Block(IEnumerable expressions) /// The created . public static BlockExpression Block(Type type, params Expression[] expressions) { - ContractUtils.RequiresNotNull(expressions, nameof(expressions)); + ArgumentNullException.ThrowIfNull(expressions); return Block(type, (IEnumerable)expressions); } @@ -970,7 +970,7 @@ public static BlockExpression Block(Type type, IEnumerable? /// The created . public static BlockExpression Block(IEnumerable? variables, IEnumerable expressions) { - ContractUtils.RequiresNotNull(expressions, nameof(expressions)); + ArgumentNullException.ThrowIfNull(expressions); ReadOnlyCollection variableList = variables.ToReadOnly(); if (variableList.Count == 0) @@ -998,8 +998,8 @@ public static BlockExpression Block(IEnumerable? variables, /// The created . public static BlockExpression Block(Type type, IEnumerable? variables, IEnumerable expressions) { - ContractUtils.RequiresNotNull(type, nameof(type)); - ContractUtils.RequiresNotNull(expressions, nameof(expressions)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(expressions); ReadOnlyCollection expressionList = expressions.ToReadOnly(); RequiresCanRead(expressionList, nameof(expressions)); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/CatchBlock.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/CatchBlock.cs index df72abf31836c9..386c4630892e94 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/CatchBlock.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/CatchBlock.cs @@ -92,7 +92,7 @@ public static CatchBlock Catch(Type type, Expression body) /// The created . public static CatchBlock Catch(ParameterExpression variable, Expression body) { - ContractUtils.RequiresNotNull(variable, nameof(variable)); + ArgumentNullException.ThrowIfNull(variable); return MakeCatchBlock(variable.Type, variable, body, filter: null); } @@ -119,7 +119,7 @@ public static CatchBlock Catch(Type type, Expression body, Expression? filter) /// The created . public static CatchBlock Catch(ParameterExpression variable, Expression body, Expression? filter) { - ContractUtils.RequiresNotNull(variable, nameof(variable)); + ArgumentNullException.ThrowIfNull(variable); return MakeCatchBlock(variable.Type, variable, body, filter); } @@ -134,7 +134,7 @@ public static CatchBlock Catch(ParameterExpression variable, Expression body, Ex /// must be non-null and match the type of (if it is supplied). public static CatchBlock MakeCatchBlock(Type type, ParameterExpression? variable, Expression body, Expression? filter) { - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); ContractUtils.Requires(variable == null || TypeUtils.AreEquivalent(variable.Type, type), nameof(variable)); if (variable == null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs index 4f0ed87b7132b2..1619aa3a0bf90b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/AssemblyGen.cs @@ -40,8 +40,8 @@ private AssemblyGen() private TypeBuilder DefineType(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type parent, TypeAttributes attr) { - ContractUtils.RequiresNotNull(name, nameof(name)); - ContractUtils.RequiresNotNull(parent, nameof(parent)); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(parent); StringBuilder sb = new StringBuilder(name); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConditionalExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConditionalExpression.cs index 3be49a5c3347c6..6ba64991f2f7a8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConditionalExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConditionalExpression.cs @@ -168,7 +168,7 @@ public static ConditionalExpression Condition(Expression test, Expression ifTrue ExpressionUtils.RequiresCanRead(test, nameof(test)); ExpressionUtils.RequiresCanRead(ifTrue, nameof(ifTrue)); ExpressionUtils.RequiresCanRead(ifFalse, nameof(ifFalse)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (test.Type != typeof(bool)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs index e4adc598570bdd..7e7e6b23a095e4 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ConstantExpression.cs @@ -94,7 +94,7 @@ public static ConstantExpression Constant(object? value) /// public static ConstantExpression Constant(object? value, Type type) { - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); if (value == null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugInfoExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugInfoExpression.cs index d27ea67ad5dfd9..ca3f0e7dd0546d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugInfoExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DebugInfoExpression.cs @@ -155,7 +155,7 @@ public partial class Expression /// An instance of . public static DebugInfoExpression DebugInfo(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn) { - ContractUtils.RequiresNotNull(document, nameof(document)); + ArgumentNullException.ThrowIfNull(document); if (startLine == 0xfeefee && startColumn == 0 && endLine == 0xfeefee && endColumn == 0) { return new ClearDebugInfoExpression(document); @@ -172,7 +172,7 @@ public static DebugInfoExpression DebugInfo(SymbolDocumentInfo document, int sta /// An instance of for clearing a sequence point. public static DebugInfoExpression ClearDebugInfo(SymbolDocumentInfo document) { - ContractUtils.RequiresNotNull(document, nameof(document)); + ArgumentNullException.ThrowIfNull(document); return new ClearDebugInfoExpression(document); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DefaultExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DefaultExpression.cs index 5e951596d8d227..b322bb322f7553 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DefaultExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DefaultExpression.cs @@ -63,7 +63,7 @@ public static DefaultExpression Empty() /// public static DefaultExpression Default(Type type) { - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); return new DefaultExpression(type); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs index 2081496c1b3993..d2e1204b2c1640 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/DynamicExpression.cs @@ -856,8 +856,8 @@ public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder bi return MakeDynamic(delegateType, binder, argumentList[0], argumentList[1], argumentList[2], argumentList[3]); } - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(delegateType); + ArgumentNullException.ThrowIfNull(binder); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); var method = GetValidMethodForDynamic(delegateType); @@ -883,8 +883,8 @@ public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder bi /// public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0) { - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(delegateType); + ArgumentNullException.ThrowIfNull(binder); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); var method = GetValidMethodForDynamic(delegateType); @@ -913,8 +913,8 @@ public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder bi /// public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1) { - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(delegateType); + ArgumentNullException.ThrowIfNull(binder); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); var method = GetValidMethodForDynamic(delegateType); @@ -946,8 +946,8 @@ public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder bi /// public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2) { - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(delegateType); + ArgumentNullException.ThrowIfNull(binder); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); var method = GetValidMethodForDynamic(delegateType); @@ -982,8 +982,8 @@ public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder bi /// public static DynamicExpression MakeDynamic(Type delegateType, CallSiteBinder binder, Expression arg0, Expression arg1, Expression arg2, Expression arg3) { - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(delegateType); + ArgumentNullException.ThrowIfNull(binder); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw Error.TypeMustBeDerivedFromSystemDelegate(); var method = GetValidMethodForDynamic(delegateType); @@ -1049,7 +1049,7 @@ public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, /// public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); ValidateDynamicArgument(arg0, nameof(arg0)); DelegateHelpers.TypeInfo info = DelegateHelpers.GetNextTypeInfo( @@ -1084,7 +1084,7 @@ public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, /// public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0, Expression arg1) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); ValidateDynamicArgument(arg0, nameof(arg0)); ValidateDynamicArgument(arg1, nameof(arg1)); @@ -1124,7 +1124,7 @@ public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, /// public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0, Expression arg1, Expression arg2) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); ValidateDynamicArgument(arg0, nameof(arg0)); ValidateDynamicArgument(arg1, nameof(arg1)); ValidateDynamicArgument(arg2, nameof(arg2)); @@ -1169,7 +1169,7 @@ public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, /// public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); ValidateDynamicArgument(arg0, nameof(arg0)); ValidateDynamicArgument(arg1, nameof(arg1)); ValidateDynamicArgument(arg2, nameof(arg2)); @@ -1215,8 +1215,8 @@ public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, /// public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, IEnumerable arguments) { - ContractUtils.RequiresNotNull(arguments, nameof(arguments)); - ContractUtils.RequiresNotNull(returnType, nameof(returnType)); + ArgumentNullException.ThrowIfNull(arguments); + ArgumentNullException.ThrowIfNull(returnType); var args = arguments.ToReadOnly(); ContractUtils.RequiresNotEmpty(args, nameof(arguments)); @@ -1225,7 +1225,7 @@ public static DynamicExpression Dynamic(CallSiteBinder binder, Type returnType, private static DynamicExpression MakeDynamic(CallSiteBinder binder, Type returnType, ReadOnlyCollection arguments) { - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); int n = arguments.Count; @@ -1260,7 +1260,7 @@ private static void ValidateDynamicArgument(Expression arg, string paramName, in { ExpressionUtils.RequiresCanRead(arg, paramName, index); var type = arg.Type; - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type), allowByRef: true, allowPointer: true); if (type == typeof(void)) throw Error.ArgumentTypeCannotBeVoid(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ElementInit.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ElementInit.cs index 111ab815461dcd..7596df3f812c52 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ElementInit.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ElementInit.cs @@ -88,8 +88,8 @@ public static ElementInit ElementInit(MethodInfo addMethod, params Expression[] /// The created expression. public static ElementInit ElementInit(MethodInfo addMethod, IEnumerable arguments) { - ContractUtils.RequiresNotNull(addMethod, nameof(addMethod)); - ContractUtils.RequiresNotNull(arguments, nameof(arguments)); + ArgumentNullException.ThrowIfNull(addMethod); + ArgumentNullException.ThrowIfNull(arguments); ReadOnlyCollection argumentsRO = arguments.ToReadOnly(); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.DebuggerProxy.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.DebuggerProxy.cs index 85064e7249a89b..de5fe863a66e76 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.DebuggerProxy.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.DebuggerProxy.cs @@ -15,7 +15,7 @@ internal sealed class BinaryExpressionProxy public BinaryExpressionProxy(BinaryExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -37,7 +37,7 @@ internal sealed class BlockExpressionProxy public BlockExpressionProxy(BlockExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -56,7 +56,7 @@ internal sealed class CatchBlockProxy public CatchBlockProxy(CatchBlock node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -72,7 +72,7 @@ internal sealed class ConditionalExpressionProxy public ConditionalExpressionProxy(ConditionalExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -91,7 +91,7 @@ internal sealed class ConstantExpressionProxy public ConstantExpressionProxy(ConstantExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -108,7 +108,7 @@ internal sealed class DebugInfoExpressionProxy public DebugInfoExpressionProxy(DebugInfoExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -130,7 +130,7 @@ internal sealed class DefaultExpressionProxy public DefaultExpressionProxy(DefaultExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -146,7 +146,7 @@ internal sealed class GotoExpressionProxy public GotoExpressionProxy(GotoExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -165,7 +165,7 @@ internal sealed class IndexExpressionProxy public IndexExpressionProxy(IndexExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -184,7 +184,7 @@ internal sealed class InvocationExpressionProxy public InvocationExpressionProxy(InvocationExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -202,7 +202,7 @@ internal sealed class LabelExpressionProxy public LabelExpressionProxy(LabelExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -220,7 +220,7 @@ internal sealed class LambdaExpressionProxy public LambdaExpressionProxy(LambdaExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -241,7 +241,7 @@ internal sealed class ListInitExpressionProxy public ListInitExpressionProxy(ListInitExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -259,7 +259,7 @@ internal sealed class LoopExpressionProxy public LoopExpressionProxy(LoopExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -278,7 +278,7 @@ internal sealed class MemberExpressionProxy public MemberExpressionProxy(MemberExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -296,7 +296,7 @@ internal sealed class MemberInitExpressionProxy public MemberInitExpressionProxy(MemberInitExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -314,7 +314,7 @@ internal sealed class MethodCallExpressionProxy public MethodCallExpressionProxy(MethodCallExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -333,7 +333,7 @@ internal sealed class NewArrayExpressionProxy public NewArrayExpressionProxy(NewArrayExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -350,7 +350,7 @@ internal sealed class NewExpressionProxy public NewExpressionProxy(NewExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -369,7 +369,7 @@ internal sealed class ParameterExpressionProxy public ParameterExpressionProxy(ParameterExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -387,7 +387,7 @@ internal sealed class RuntimeVariablesExpressionProxy public RuntimeVariablesExpressionProxy(RuntimeVariablesExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -404,7 +404,7 @@ internal sealed class SwitchCaseProxy public SwitchCaseProxy(SwitchCase node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -418,7 +418,7 @@ internal sealed class SwitchExpressionProxy public SwitchExpressionProxy(SwitchExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -438,7 +438,7 @@ internal sealed class TryExpressionProxy public TryExpressionProxy(TryExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -458,7 +458,7 @@ internal sealed class TypeBinaryExpressionProxy public TypeBinaryExpressionProxy(TypeBinaryExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } @@ -476,7 +476,7 @@ internal sealed class UnaryExpressionProxy public UnaryExpressionProxy(UnaryExpression node) { - ContractUtils.RequiresNotNull(node, nameof(node)); + ArgumentNullException.ThrowIfNull(node); _node = node; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs index 998bc54fcbb732..1f522c0f8d3b25 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Expression.cs @@ -240,10 +240,7 @@ private static void RequiresCanRead(IReadOnlyList items, string para private static void RequiresCanWrite(Expression expression, string paramName) { - if (expression == null) - { - throw new ArgumentNullException(paramName); - } + ArgumentNullException.ThrowIfNull(expression, paramName); switch (expression.NodeType) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs index 92e210f97690bb..f44061ea680a77 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionVisitor.cs @@ -42,7 +42,7 @@ protected ExpressionVisitor() /// otherwise, returns the original expression list. public ReadOnlyCollection Visit(ReadOnlyCollection nodes) { - ContractUtils.RequiresNotNull(nodes, nameof(nodes)); + ArgumentNullException.ThrowIfNull(nodes); Expression[]? newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { @@ -90,8 +90,8 @@ public ReadOnlyCollection Visit(ReadOnlyCollection nodes /// otherwise, returns the original node list. public static ReadOnlyCollection Visit(ReadOnlyCollection nodes, Func elementVisitor) { - ContractUtils.RequiresNotNull(nodes, nameof(nodes)); - ContractUtils.RequiresNotNull(elementVisitor, nameof(elementVisitor)); + ArgumentNullException.ThrowIfNull(nodes); + ArgumentNullException.ThrowIfNull(elementVisitor); T[]? newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { @@ -152,7 +152,7 @@ public static ReadOnlyCollection Visit(ReadOnlyCollection nodes, FuncThe visit method for this node returned a different type. public ReadOnlyCollection VisitAndConvert(ReadOnlyCollection nodes, string? callerName) where T : Expression { - ContractUtils.RequiresNotNull(nodes, nameof(nodes)); + ArgumentNullException.ThrowIfNull(nodes); T[]? newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs index 9c1a38f9a8a458..8ec977816a6c0a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/GotoExpression.cs @@ -338,7 +338,7 @@ public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget targe private static void ValidateGoto(LabelTarget target, ref Expression? value, string targetParameter, string valueParameter, Type? type) { - ContractUtils.RequiresNotNull(target, targetParameter); + ArgumentNullException.ThrowIfNull(target, targetParameter); if (value == null) { if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression(nameof(target)); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs index 47c2a4d1ffe058..1d5c8c79398e2c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/IndexExpression.cs @@ -213,7 +213,7 @@ public static IndexExpression ArrayAccess(Expression array, IEnumerable arguments, string? paramName) { - ContractUtils.RequiresNotNull(arguments, nameof(arguments)); + ArgumentNullException.ThrowIfNull(arguments); ValidateMethodInfo(method, nameof(method)); if ((method.CallingConvention & CallingConventions.VarArgs) != 0) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs index 7122ddd021ea83..16362b337db7fb 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs @@ -43,7 +43,7 @@ internal sealed class DebugView public DebugView(InstructionArray array) { - ContractUtils.RequiresNotNull(array, nameof(array)); + ArgumentNullException.ThrowIfNull(array); _array = array; } @@ -88,7 +88,7 @@ internal sealed class DebugView public DebugView(InstructionList list) { - ContractUtils.RequiresNotNull(list, nameof(list)); + ArgumentNullException.ThrowIfNull(list); _list = list; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs index 509d4ae8dcfe52..18a2e3ca3c572f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs @@ -126,7 +126,7 @@ public void Dup() public static bool IsInterpretedFrame(MethodBase method) { - //ContractUtils.RequiresNotNull(method, nameof(method)); + //ArgumentNullException.ThrowIfNull(method); return method.DeclaringType == typeof(Interpreter) && method.Name == "Run"; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LabelTarget.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LabelTarget.cs index b8b8d33fd42097..1468744d32752b 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LabelTarget.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LabelTarget.cs @@ -77,7 +77,7 @@ public static LabelTarget Label(Type type) /// The new . public static LabelTarget Label(Type type, string? name) { - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); return new LabelTarget(type, name); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs index 35c0c9cb92874b..0743941798877f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/LambdaExpression.cs @@ -169,7 +169,7 @@ public Delegate Compile(bool preferInterpretation) /// A which will be used to hold the lambda's IL. public void CompileToMethod(System.Reflection.Emit.MethodBuilder method) { - ContractUtils.RequiresNotNull(method, nameof(method)); + ArgumentNullException.ThrowIfNull(method); ContractUtils.Requires(method.IsStatic, nameof(method)); var type = method.DeclaringType as System.Reflection.Emit.TypeBuilder; if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder(); @@ -846,7 +846,7 @@ public static LambdaExpression Lambda(Expression body, string? name, IEnumerable /// A that has the property equal to and the and properties set to the specified values. public static LambdaExpression Lambda(Expression body, string? name, bool tailCall, IEnumerable? parameters) { - ContractUtils.RequiresNotNull(body, nameof(body)); + ArgumentNullException.ThrowIfNull(body); ReadOnlyCollection parameterList = parameters.ToReadOnly(); @@ -858,7 +858,7 @@ public static LambdaExpression Lambda(Expression body, string? name, bool tailCa for (int i = 0; i < paramCount; i++) { ParameterExpression param = parameterList[i]; - ContractUtils.RequiresNotNull(param, "parameter"); + ArgumentNullException.ThrowIfNull(param, "parameter"); typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type; if (!set.Add(param)) { @@ -908,7 +908,7 @@ public static LambdaExpression Lambda(Type delegateType, Expression body, string private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection parameters, string paramName) { - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); + ArgumentNullException.ThrowIfNull(delegateType); ExpressionUtils.RequiresCanRead(body, nameof(body)); if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs index b017dddf8e5c23..a786f057d4300f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/ListInitExpression.cs @@ -119,8 +119,8 @@ public static ListInitExpression ListInit(NewExpression newExpression, params Ex [RequiresUnreferencedCode(ExpressionRequiresUnreferencedCode)] public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable initializers) { - ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); - ContractUtils.RequiresNotNull(initializers, nameof(initializers)); + ArgumentNullException.ThrowIfNull(newExpression); + ArgumentNullException.ThrowIfNull(initializers); ReadOnlyCollection initializerlist = initializers.ToReadOnly(); if (initializerlist.Count == 0) @@ -159,8 +159,8 @@ public static ListInitExpression ListInit(NewExpression newExpression, MethodInf { return ListInit(newExpression, initializers); } - ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); - ContractUtils.RequiresNotNull(initializers, nameof(initializers)); + ArgumentNullException.ThrowIfNull(newExpression); + ArgumentNullException.ThrowIfNull(initializers); ReadOnlyCollection initializerlist = initializers.ToReadOnly(); ElementInit[] initList = new ElementInit[initializerlist.Count]; @@ -201,8 +201,8 @@ public static ListInitExpression ListInit(NewExpression newExpression, params El /// public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable initializers) { - ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); - ContractUtils.RequiresNotNull(initializers, nameof(initializers)); + ArgumentNullException.ThrowIfNull(newExpression); + ArgumentNullException.ThrowIfNull(initializers); ReadOnlyCollection initializerlist = initializers.ToReadOnly(); ValidateListInitArgs(newExpression.Type, initializerlist, nameof(newExpression)); return new ListInitExpression(newExpression, initializerlist); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs index 2226b7f5a988cf..c757db1a168d57 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberAssignment.cs @@ -58,7 +58,7 @@ public partial class Expression /// The created . public static MemberAssignment Bind(MemberInfo member, Expression expression) { - ContractUtils.RequiresNotNull(member, nameof(member)); + ArgumentNullException.ThrowIfNull(member); ExpressionUtils.RequiresCanRead(expression, nameof(expression)); Type memberType; ValidateSettableFieldOrPropertyMember(member, out memberType); @@ -78,8 +78,8 @@ public static MemberAssignment Bind(MemberInfo member, Expression expression) [RequiresUnreferencedCode(PropertyFromAccessorRequiresUnreferencedCode)] public static MemberAssignment Bind(MethodInfo propertyAccessor, Expression expression) { - ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor)); - ContractUtils.RequiresNotNull(expression, nameof(expression)); + ArgumentNullException.ThrowIfNull(propertyAccessor); + ArgumentNullException.ThrowIfNull(expression); ValidateMethodInfo(propertyAccessor, nameof(propertyAccessor)); return Bind(GetProperty(propertyAccessor, nameof(propertyAccessor)), expression); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs index 1e9ff0179a5d1a..6e053713427e5e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberExpression.cs @@ -126,7 +126,7 @@ public partial class Expression /// The created . public static MemberExpression Field(Expression? expression, FieldInfo field) { - ContractUtils.RequiresNotNull(field, nameof(field)); + ArgumentNullException.ThrowIfNull(field); if (field.IsStatic) { @@ -154,7 +154,7 @@ public static MemberExpression Field(Expression? expression, FieldInfo field) public static MemberExpression Field(Expression expression, string fieldName) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(fieldName, nameof(fieldName)); + ArgumentNullException.ThrowIfNull(fieldName); // bind to public names first FieldInfo? fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) @@ -178,8 +178,8 @@ public static MemberExpression Field( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] Type type, string fieldName) { - ContractUtils.RequiresNotNull(type, nameof(type)); - ContractUtils.RequiresNotNull(fieldName, nameof(fieldName)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(fieldName); // bind to public names first FieldInfo? fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) @@ -206,7 +206,7 @@ public static MemberExpression Field( public static MemberExpression Property(Expression expression, string propertyName) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(propertyName, nameof(propertyName)); + ArgumentNullException.ThrowIfNull(propertyName); // bind to public names first PropertyInfo? pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) ?? expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); @@ -229,8 +229,8 @@ public static MemberExpression Property( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties| DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, string propertyName) { - ContractUtils.RequiresNotNull(type, nameof(type)); - ContractUtils.RequiresNotNull(propertyName, nameof(propertyName)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(propertyName); // bind to public names first PropertyInfo? pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy) ?? type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); @@ -249,7 +249,7 @@ public static MemberExpression Property( /// The created . public static MemberExpression Property(Expression? expression, PropertyInfo property) { - ContractUtils.RequiresNotNull(property, nameof(property)); + ArgumentNullException.ThrowIfNull(property); MethodInfo? mi = property.GetGetMethod(nonPublic: true); @@ -299,7 +299,7 @@ public static MemberExpression Property(Expression? expression, PropertyInfo pro [RequiresUnreferencedCode(PropertyFromAccessorRequiresUnreferencedCode)] public static MemberExpression Property(Expression? expression, MethodInfo propertyAccessor) { - ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor)); + ArgumentNullException.ThrowIfNull(propertyAccessor); ValidateMethodInfo(propertyAccessor, nameof(propertyAccessor)); return Property(expression, GetProperty(propertyAccessor, nameof(propertyAccessor))); } @@ -385,7 +385,7 @@ public static MemberExpression PropertyOrField(Expression expression, string pro /// The created . public static MemberExpression MakeMemberAccess(Expression? expression, MemberInfo member) { - ContractUtils.RequiresNotNull(member, nameof(member)); + ArgumentNullException.ThrowIfNull(member); if (member is FieldInfo fi) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs index 9785b5d2844cbd..b554c066ac8ca5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberInitExpression.cs @@ -156,8 +156,8 @@ public static MemberInitExpression MemberInit(NewExpression newExpression, param /// The property of an element of does not represent a member of the type that .Type represents. public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable bindings) { - ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); - ContractUtils.RequiresNotNull(bindings, nameof(bindings)); + ArgumentNullException.ThrowIfNull(newExpression); + ArgumentNullException.ThrowIfNull(bindings); ReadOnlyCollection roBindings = bindings.ToReadOnly(); ValidateMemberInitArgs(newExpression.Type, roBindings); return new MemberInitExpression(newExpression, roBindings); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs index fbf4bb8ac97fc2..31b7f7e2af8a07 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberListBinding.cs @@ -79,8 +79,8 @@ public static MemberListBinding ListBind(MemberInfo member, params ElementInit[] /// does not represent a field or property.-or-The or of the field or property that represents does not implement . public static MemberListBinding ListBind(MemberInfo member, IEnumerable initializers) { - ContractUtils.RequiresNotNull(member, nameof(member)); - ContractUtils.RequiresNotNull(initializers, nameof(initializers)); + ArgumentNullException.ThrowIfNull(member); + ArgumentNullException.ThrowIfNull(initializers); Type memberType; ValidateGettableFieldOrPropertyMember(member, out memberType); ReadOnlyCollection initList = initializers.ToReadOnly(); @@ -113,8 +113,8 @@ public static MemberListBinding ListBind(MethodInfo propertyAccessor, params Ele [RequiresUnreferencedCode(PropertyFromAccessorRequiresUnreferencedCode)] public static MemberListBinding ListBind(MethodInfo propertyAccessor, IEnumerable initializers) { - ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor)); - ContractUtils.RequiresNotNull(initializers, nameof(initializers)); + ArgumentNullException.ThrowIfNull(propertyAccessor); + ArgumentNullException.ThrowIfNull(initializers); return ListBind(GetProperty(propertyAccessor, nameof(propertyAccessor)), initializers); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs index 54a90a7fa59454..19b223031ddb9d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs @@ -78,8 +78,8 @@ public static MemberMemberBinding MemberBind(MemberInfo member, params MemberBin /// A that has the property equal to and the and properties set to the specified values. public static MemberMemberBinding MemberBind(MemberInfo member, IEnumerable bindings) { - ContractUtils.RequiresNotNull(member, nameof(member)); - ContractUtils.RequiresNotNull(bindings, nameof(bindings)); + ArgumentNullException.ThrowIfNull(member); + ArgumentNullException.ThrowIfNull(bindings); ReadOnlyCollection roBindings = bindings.ToReadOnly(); Type memberType; ValidateGettableFieldOrPropertyMember(member, out memberType); @@ -116,7 +116,7 @@ public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, params [RequiresUnreferencedCode(PropertyFromAccessorRequiresUnreferencedCode)] public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, IEnumerable bindings) { - ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor)); + ArgumentNullException.ThrowIfNull(propertyAccessor); return MemberBind(GetProperty(propertyAccessor, nameof(propertyAccessor)), bindings); } @@ -155,7 +155,7 @@ private static void ValidateMemberInitArgs(Type type, ReadOnlyCollection is null. public static MethodCallExpression Call(MethodInfo method, Expression arg0) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method); @@ -879,9 +879,9 @@ public static MethodCallExpression Call(MethodInfo method, Expression arg0) /// is null. public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); - ContractUtils.RequiresNotNull(arg1, nameof(arg1)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); + ArgumentNullException.ThrowIfNull(arg1); ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method); @@ -903,10 +903,10 @@ public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expr /// is null. public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); - ContractUtils.RequiresNotNull(arg1, nameof(arg1)); - ContractUtils.RequiresNotNull(arg2, nameof(arg2)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); + ArgumentNullException.ThrowIfNull(arg1); + ArgumentNullException.ThrowIfNull(arg2); ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method); @@ -930,11 +930,11 @@ public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expr /// is null. public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); - ContractUtils.RequiresNotNull(arg1, nameof(arg1)); - ContractUtils.RequiresNotNull(arg2, nameof(arg2)); - ContractUtils.RequiresNotNull(arg3, nameof(arg3)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); + ArgumentNullException.ThrowIfNull(arg1); + ArgumentNullException.ThrowIfNull(arg2); + ArgumentNullException.ThrowIfNull(arg3); ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method); @@ -961,12 +961,12 @@ public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expr /// A that has the property equal to and the and properties set to the specified values. public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); - ContractUtils.RequiresNotNull(arg1, nameof(arg1)); - ContractUtils.RequiresNotNull(arg2, nameof(arg2)); - ContractUtils.RequiresNotNull(arg3, nameof(arg3)); - ContractUtils.RequiresNotNull(arg4, nameof(arg4)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); + ArgumentNullException.ThrowIfNull(arg1); + ArgumentNullException.ThrowIfNull(arg2); + ArgumentNullException.ThrowIfNull(arg3); + ArgumentNullException.ThrowIfNull(arg4); ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method); @@ -1011,7 +1011,7 @@ public static MethodCallExpression Call(MethodInfo method, IEnumerableA that has the property equal to and the and properties set to the specified values. public static MethodCallExpression Call(Expression? instance, MethodInfo method) { - ContractUtils.RequiresNotNull(method, nameof(method)); + ArgumentNullException.ThrowIfNull(method); ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method); @@ -1048,8 +1048,8 @@ internal static MethodCallExpression Call(Expression? instance, MethodInfo metho { // COMPAT: This method is marked as non-public to ensure compile-time compatibility for Expression.Call(e, m, null). - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method); @@ -1075,9 +1075,9 @@ internal static MethodCallExpression Call(Expression? instance, MethodInfo metho /// A that has the property equal to and the and properties set to the specified values. public static MethodCallExpression Call(Expression? instance, MethodInfo method, Expression arg0, Expression arg1) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); - ContractUtils.RequiresNotNull(arg1, nameof(arg1)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); + ArgumentNullException.ThrowIfNull(arg1); ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method); @@ -1105,10 +1105,10 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, /// A that has the property equal to and the and properties set to the specified values. public static MethodCallExpression Call(Expression? instance, MethodInfo method, Expression arg0, Expression arg1, Expression arg2) { - ContractUtils.RequiresNotNull(method, nameof(method)); - ContractUtils.RequiresNotNull(arg0, nameof(arg0)); - ContractUtils.RequiresNotNull(arg1, nameof(arg1)); - ContractUtils.RequiresNotNull(arg2, nameof(arg2)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(arg0); + ArgumentNullException.ThrowIfNull(arg1); + ArgumentNullException.ThrowIfNull(arg2); ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method); @@ -1140,8 +1140,8 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, [RequiresUnreferencedCode(ExpressionRequiresUnreferencedCode)] public static MethodCallExpression Call(Expression instance, string methodName, Type[]? typeArguments, params Expression[]? arguments) { - ContractUtils.RequiresNotNull(instance, nameof(instance)); - ContractUtils.RequiresNotNull(methodName, nameof(methodName)); + ArgumentNullException.ThrowIfNull(instance); + ArgumentNullException.ThrowIfNull(methodName); if (arguments == null) { arguments = Array.Empty(); @@ -1170,8 +1170,8 @@ public static MethodCallExpression Call( Type[]? typeArguments, params Expression[]? arguments) { - ContractUtils.RequiresNotNull(type, nameof(type)); - ContractUtils.RequiresNotNull(methodName, nameof(methodName)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(methodName); if (arguments == null) arguments = Array.Empty(); BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy; @@ -1216,7 +1216,7 @@ public static MethodCallExpression Call(Expression? instance, MethodInfo method, } } - ContractUtils.RequiresNotNull(method, nameof(method)); + ArgumentNullException.ThrowIfNull(method); // If this has resulted in a duplicate call to ToReadOnly (any case except arguments being // a large IReadOnlyList that is not TrueReadOnlyCollection) it will return argumentList @@ -1352,7 +1352,7 @@ private static bool IsCompatible(MethodBase m, Expression[] arguments) for (int i = 0; i < arguments.Length; i++) { Expression arg = arguments[i]; - ContractUtils.RequiresNotNull(arg, nameof(arguments)); + ArgumentNullException.ThrowIfNull(arg, nameof(arguments)); Type argType = arg.Type; Type pType = parms[i].ParameterType; if (pType.IsByRef) @@ -1408,7 +1408,7 @@ public static MethodCallExpression ArrayIndex(Expression array, params Expressio public static MethodCallExpression ArrayIndex(Expression array, IEnumerable indexes) { ExpressionUtils.RequiresCanRead(array, nameof(array), -1); - ContractUtils.RequiresNotNull(indexes, nameof(indexes)); + ArgumentNullException.ThrowIfNull(indexes); Type arrayType = array.Type; if (!arrayType.IsArray) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs index e3e3b882d1308e..9f6fa33f801a86 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewArrayExpression.cs @@ -63,7 +63,7 @@ protected internal override Expression Accept(ExpressionVisitor visitor) public NewArrayExpression Update(IEnumerable expressions) { // Explicit null check here as otherwise wrong parameter name will be used. - ContractUtils.RequiresNotNull(expressions, nameof(expressions)); + ArgumentNullException.ThrowIfNull(expressions); if (ExpressionUtils.SameElements(ref expressions!, Expressions)) { @@ -128,8 +128,8 @@ public static NewArrayExpression NewArrayInit(Type type, params Expression[] ini /// A that has the property equal to and the property set to the specified value. public static NewArrayExpression NewArrayInit(Type type, IEnumerable initializers) { - ContractUtils.RequiresNotNull(type, nameof(type)); - ContractUtils.RequiresNotNull(initializers, nameof(initializers)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(initializers); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(nameof(type)); @@ -195,8 +195,8 @@ public static NewArrayExpression NewArrayBounds(Type type, params Expression[] b /// A that has the property equal to and the property set to the specified value. public static NewArrayExpression NewArrayBounds(Type type, IEnumerable bounds) { - ContractUtils.RequiresNotNull(type, nameof(type)); - ContractUtils.RequiresNotNull(bounds, nameof(bounds)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(bounds); if (type == typeof(void)) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs index 7f7969042cf15b..ec414a0006e00d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/NewExpression.cs @@ -135,8 +135,14 @@ public static NewExpression New(ConstructorInfo constructor, params Expression[] /// A that has the property equal to and the and properties set to the specified value. public static NewExpression New(ConstructorInfo constructor, IEnumerable? arguments) { - ContractUtils.RequiresNotNull(constructor, nameof(constructor)); - ContractUtils.RequiresNotNull(constructor.DeclaringType!, nameof(constructor) + "." + nameof(constructor.DeclaringType)); + ArgumentNullException.ThrowIfNull(constructor); + ArgumentNullException.ThrowIfNull(constructor.DeclaringType, nameof(constructor)); + if (constructor.DeclaringType is null) + { +#pragma warning disable CA2208 + throw new ArgumentNullException($"{nameof(constructor)}.{nameof(constructor.DeclaringType)}"); +#pragma warning restore CA2208 + } TypeUtils.ValidateType(constructor.DeclaringType!, nameof(constructor), allowByRef: true, allowPointer: true); ValidateConstructor(constructor, nameof(constructor)); ReadOnlyCollection argList = arguments.ToReadOnly(); @@ -155,8 +161,13 @@ public static NewExpression New(ConstructorInfo constructor, IEnumerable? arguments, IEnumerable? members) { - ContractUtils.RequiresNotNull(constructor, nameof(constructor)); - ContractUtils.RequiresNotNull(constructor.DeclaringType!, nameof(constructor) + "." + nameof(constructor.DeclaringType)); + ArgumentNullException.ThrowIfNull(constructor); + if (constructor.DeclaringType is null) + { +#pragma warning disable CA2208 + throw new ArgumentNullException($"{nameof(constructor)}.{nameof(constructor.DeclaringType)}"); +#pragma warning restore CA2208 + } TypeUtils.ValidateType(constructor.DeclaringType!, nameof(constructor), allowByRef: true, allowPointer: true); ValidateConstructor(constructor, nameof(constructor)); ReadOnlyCollection memberList = members.ToReadOnly(); @@ -186,7 +197,7 @@ public static NewExpression New(ConstructorInfo constructor, IEnumerableAn instance of that has the property equal to and the property set to the specified value. public static RuntimeVariablesExpression RuntimeVariables(IEnumerable variables) { - ContractUtils.RequiresNotNull(variables, nameof(variables)); + ArgumentNullException.ThrowIfNull(variables); ReadOnlyCollection vars = variables.ToReadOnly(); for (int i = 0; i < vars.Count; i++) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs index f46c49fb8bf4e6..ce6575bd6e457d 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SwitchExpression.cs @@ -218,7 +218,7 @@ public static SwitchExpression Switch(Type? type, Expression switchValue, Expres ParameterInfo rightParam = pms[1]; foreach (SwitchCase c in caseList) { - ContractUtils.RequiresNotNull(c, nameof(cases)); + ArgumentNullException.ThrowIfNull(c, nameof(cases)); ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases)); for (int i = 0, n = c.TestValues.Count; i < n; i++) { @@ -253,7 +253,7 @@ public static SwitchExpression Switch(Type? type, Expression switchValue, Expres Expression firstTestValue = caseList[0].TestValues[0]; foreach (SwitchCase c in caseList) { - ContractUtils.RequiresNotNull(c, nameof(cases)); + ArgumentNullException.ThrowIfNull(c, nameof(cases)); ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases)); // When no comparison method is provided, require all test values to have the same type. for (int i = 0, n = c.TestValues.Count; i < n; i++) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SymbolDocumentInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SymbolDocumentInfo.cs index 542c3a5ac7070b..f7960b71645ebb 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SymbolDocumentInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/SymbolDocumentInfo.cs @@ -13,7 +13,7 @@ public class SymbolDocumentInfo { internal SymbolDocumentInfo(string fileName) { - ContractUtils.RequiresNotNull(fileName, nameof(fileName)); + ArgumentNullException.ThrowIfNull(fileName); FileName = fileName; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs index 2a4ce5e2f763e3..037015541be06c 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/TypeBinaryExpression.cs @@ -191,7 +191,7 @@ public partial class Expression public static TypeBinaryExpression TypeIs(Expression expression, Type type) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type)); return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs); @@ -206,7 +206,7 @@ public static TypeBinaryExpression TypeIs(Expression expression, Type type) public static TypeBinaryExpression TypeEqual(Expression expression, Type type) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (type.IsByRef) throw Error.TypeMustNotBeByRef(nameof(type)); return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs index eea96673e50a9a..3788e014a5d93a 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/UnaryExpression.cs @@ -690,7 +690,7 @@ public static UnaryExpression OnesComplement(Expression expression, MethodInfo? public static UnaryExpression TypeAs(Expression expression, Type type) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); if (type.IsValueType && !type.IsNullableType()) { @@ -709,7 +709,7 @@ public static UnaryExpression TypeAs(Expression expression, Type type) public static UnaryExpression Unbox(Expression expression, Type type) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (!expression.Type.IsInterface && expression.Type != typeof(object)) { throw Error.InvalidUnboxType(nameof(expression)); @@ -745,7 +745,7 @@ public static UnaryExpression Convert(Expression expression, Type type) public static UnaryExpression Convert(Expression expression, Type type, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); if (method == null) { @@ -785,7 +785,7 @@ public static UnaryExpression ConvertChecked(Expression expression, Type type) public static UnaryExpression ConvertChecked(Expression expression, Type type, MethodInfo? method) { ExpressionUtils.RequiresCanRead(expression, nameof(expression)); - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); if (method == null) { @@ -879,7 +879,7 @@ public static UnaryExpression Throw(Expression? value) /// A that represents the exception. public static UnaryExpression Throw(Expression? value, Type type) { - ContractUtils.RequiresNotNull(type, nameof(type)); + ArgumentNullException.ThrowIfNull(type); TypeUtils.ValidateType(type, nameof(type)); if (value != null) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs index b080df42bc45e5..db739708ff44b7 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs @@ -82,8 +82,8 @@ internal CallSite(CallSiteBinder? binder) /// The new CallSite. public static CallSite Create(Type delegateType, CallSiteBinder binder) { - ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(delegateType); + ArgumentNullException.ThrowIfNull(binder); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate(); CacheDict>? ctors = s_siteCtors; @@ -209,7 +209,7 @@ internal void ReleaseMatchmaker(CallSite matchMaker) public static CallSite Create(CallSiteBinder binder) { if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate(); - ContractUtils.RequiresNotNull(binder, nameof(binder)); + ArgumentNullException.ThrowIfNull(binder); return new CallSite(binder); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs index 20803ebc1cc8bf..6ee850d39943fe 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs @@ -42,8 +42,10 @@ public DynamicAttribute() /// normally, in which case the appropriate attribute specification should /// use a transformFlags value of { false, true, false }. /// - public DynamicAttribute(bool[] transformFlags!!) + public DynamicAttribute(bool[] transformFlags) { + ArgumentNullException.ThrowIfNull(transformFlags); + _transformFlags = transformFlags; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs index 4a571f1a69a0db..ba48c488c4e505 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/ReadOnlyCollectionBuilder.cs @@ -46,8 +46,10 @@ public ReadOnlyCollectionBuilder(int capacity) /// Constructs a , copying contents of the given collection. /// /// The collection whose elements to copy to the builder. - public ReadOnlyCollectionBuilder(IEnumerable collection!!) + public ReadOnlyCollectionBuilder(IEnumerable collection) { + ArgumentNullException.ThrowIfNull(collection); + if (collection is ICollection c) { int count = c.Count; @@ -379,8 +381,10 @@ void IList.Remove(object? value) #region ICollection Members - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(nameof(array)); diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs index 0602fd69596841..96e7aa1a6b47e9 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs @@ -93,8 +93,10 @@ public static class ParallelEnumerable /// /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery AsParallel(this IEnumerable source!!) + public static ParallelQuery AsParallel(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return new ParallelEnumerableWrapper(source); } @@ -113,8 +115,10 @@ public static ParallelQuery AsParallel(this IEnumerable /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery AsParallel(this Partitioner source!!) + public static ParallelQuery AsParallel(this Partitioner source) { + ArgumentNullException.ThrowIfNull(source); + return new PartitionerQueryOperator(source); } @@ -138,8 +142,10 @@ public static ParallelQuery AsParallel(this Partitioner /// The source sequence which will maintain ordering in the query. - public static ParallelQuery AsOrdered(this ParallelQuery source!!) + public static ParallelQuery AsOrdered(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + if (!(source is ParallelEnumerableWrapper || source is IParallelPartitionable)) { if (source is PartitionerQueryOperator partitionerOp) @@ -176,8 +182,10 @@ public static ParallelQuery AsOrdered(this ParallelQuery /// The source sequence which will maintain ordering in the query. - public static ParallelQuery AsOrdered(this ParallelQuery source!!) + public static ParallelQuery AsOrdered(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + ParallelEnumerableWrapper? wrapper = source as ParallelEnumerableWrapper; if (wrapper == null) { @@ -200,8 +208,10 @@ public static ParallelQuery AsOrdered(this ParallelQuery source!!) /// /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery AsUnordered(this ParallelQuery source!!) + public static ParallelQuery AsUnordered(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new OrderingQueryOperator(QueryOperator.AsQueryOperator(source), false); } @@ -217,8 +227,10 @@ public static ParallelQuery AsUnordered(this ParallelQuery /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery AsParallel(this IEnumerable source!!) + public static ParallelQuery AsParallel(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return new ParallelEnumerableWrapper(source); } @@ -242,8 +254,9 @@ public static ParallelQuery AsParallel(this IEnumerable source!!) /// /// is a null reference (Nothing in Visual Basic). /// - public static IEnumerable AsSequential(this ParallelQuery source!!) + public static IEnumerable AsSequential(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); // Ditch the wrapper, if there is one. if (source is ParallelEnumerableWrapper wrapper) @@ -273,8 +286,10 @@ public static IEnumerable AsSequential(this ParallelQuery /// is less than 1 or greater than 512. /// - public static ParallelQuery WithDegreeOfParallelism(this ParallelQuery source!!, int degreeOfParallelism) + public static ParallelQuery WithDegreeOfParallelism(this ParallelQuery source, int degreeOfParallelism) { + ArgumentNullException.ThrowIfNull(source); + if (degreeOfParallelism < 1 || degreeOfParallelism > Scheduling.MAX_SUPPORTED_DOP) { throw new ArgumentOutOfRangeException(nameof(degreeOfParallelism)); @@ -301,8 +316,10 @@ public static ParallelQuery WithDegreeOfParallelism(this Paral /// /// WithCancellation is used multiple times in the query. /// - public static ParallelQuery WithCancellation(this ParallelQuery source!!, CancellationToken cancellationToken) + public static ParallelQuery WithCancellation(this ParallelQuery source, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(source); + QuerySettings settings = QuerySettings.Empty; settings.CancellationState = new CancellationState(cancellationToken); @@ -327,8 +344,10 @@ public static ParallelQuery WithCancellation(this ParallelQuer /// /// WithExecutionMode is used multiple times in the query. /// - public static ParallelQuery WithExecutionMode(this ParallelQuery source!!, ParallelExecutionMode executionMode) + public static ParallelQuery WithExecutionMode(this ParallelQuery source, ParallelExecutionMode executionMode) { + ArgumentNullException.ThrowIfNull(source); + if (executionMode != ParallelExecutionMode.Default && executionMode != ParallelExecutionMode.ForceParallelism) { throw new ArgumentException(SR.ParallelEnumerable_WithQueryExecutionMode_InvalidMode); @@ -358,8 +377,10 @@ public static ParallelQuery WithExecutionMode(this ParallelQue /// /// WithMergeOptions is used multiple times in the query. /// - public static ParallelQuery WithMergeOptions(this ParallelQuery source!!, ParallelMergeOptions mergeOptions) + public static ParallelQuery WithMergeOptions(this ParallelQuery source, ParallelMergeOptions mergeOptions) { + ArgumentNullException.ThrowIfNull(source); + if (mergeOptions != ParallelMergeOptions.Default && mergeOptions != ParallelMergeOptions.AutoBuffered && mergeOptions != ParallelMergeOptions.NotBuffered @@ -469,8 +490,11 @@ public static ParallelQuery Empty() /// /// The query was canceled. /// - public static void ForAll(this ParallelQuery source!!, Action action!!) + public static void ForAll(this ParallelQuery source, Action action) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(action); + // We just instantiate the forall operator and invoke it synchronously on this thread. // By the time it returns, the entire query has been executed and the actions run.. new ForAllOperator(source, action).RunSynchronously(); @@ -498,8 +522,11 @@ public static void ForAll(this ParallelQuery source!!, Action< /// /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Where(this ParallelQuery source!!, Func predicate!!) + public static ParallelQuery Where(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new WhereQueryOperator(source, predicate); } @@ -513,8 +540,11 @@ public static ParallelQuery Where(this ParallelQuery /// /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Where(this ParallelQuery source!!, Func predicate!!) + public static ParallelQuery Where(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new IndexedWhereQueryOperator(source, predicate); } @@ -536,8 +566,11 @@ public static ParallelQuery Where(this ParallelQuery /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Select( - this ParallelQuery source!!, Func selector!!) + this ParallelQuery source, Func selector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + return new SelectQueryOperator(source, selector); } @@ -554,8 +587,11 @@ public static ParallelQuery Select( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Select( - this ParallelQuery source!!, Func selector!!) + this ParallelQuery source, Func selector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + return new IndexedSelectQueryOperator(source, selector); } @@ -581,8 +617,12 @@ public static ParallelQuery Select( /// or or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Zip( - this ParallelQuery first!!, ParallelQuery second!!, Func resultSelector!!) + this ParallelQuery first, ParallelQuery second, Func resultSelector) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + ArgumentNullException.ThrowIfNull(resultSelector); + return new ZipQueryOperator(first, second, resultSelector); } @@ -698,10 +738,16 @@ public static ParallelQuery Join( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Join( - this ParallelQuery outer!!, ParallelQuery inner!!, - Func outerKeySelector!!, Func innerKeySelector!!, - Func resultSelector!!, IEqualityComparer? comparer) + this ParallelQuery outer, ParallelQuery inner, + Func outerKeySelector, Func innerKeySelector, + Func resultSelector, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + return new JoinQueryOperator( outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } @@ -826,10 +872,16 @@ public static ParallelQuery GroupJoin( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery GroupJoin( - this ParallelQuery outer!!, ParallelQuery inner!!, - Func outerKeySelector!!, Func innerKeySelector!!, - Func, TResult> resultSelector!!, IEqualityComparer? comparer) + this ParallelQuery outer, ParallelQuery inner, + Func outerKeySelector, Func innerKeySelector, + Func, TResult> resultSelector, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + return new GroupJoinQueryOperator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } @@ -885,8 +937,11 @@ public static ParallelQuery GroupJoin( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery SelectMany( - this ParallelQuery source!!, Func> selector!!) + this ParallelQuery source, Func> selector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + return new SelectManyQueryOperator(source, selector, null, null); } @@ -905,8 +960,11 @@ public static ParallelQuery SelectMany( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery SelectMany( - this ParallelQuery source!!, Func> selector!!) + this ParallelQuery source, Func> selector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + return new SelectManyQueryOperator(source, null, selector, null); } @@ -931,9 +989,13 @@ public static ParallelQuery SelectMany( /// is a null reference (Nothing in Visual Basic). /// public static ParallelQuery SelectMany( - this ParallelQuery source!!, Func> collectionSelector!!, - Func resultSelector!!) + this ParallelQuery source, Func> collectionSelector, + Func resultSelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); + return new SelectManyQueryOperator(source, collectionSelector, null, resultSelector); } @@ -963,9 +1025,13 @@ public static ParallelQuery SelectMany( /// is a null reference (Nothing in Visual Basic). /// public static ParallelQuery SelectMany( - this ParallelQuery source!!, Func> collectionSelector!!, - Func resultSelector!!) + this ParallelQuery source, Func> collectionSelector, + Func resultSelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); + return new SelectManyQueryOperator(source, null, collectionSelector, resultSelector); } @@ -994,8 +1060,11 @@ public static ParallelQuery SelectMany( /// or is a null reference (Nothing in Visual Basic). /// public static OrderedParallelQuery OrderBy( - this ParallelQuery source!!, Func keySelector!!) + this ParallelQuery source, Func keySelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( new SortQueryOperator(source, keySelector, null, false)); } @@ -1019,8 +1088,11 @@ public static OrderedParallelQuery OrderBy( /// or is a null reference (Nothing in Visual Basic). /// public static OrderedParallelQuery OrderBy( - this ParallelQuery source!!, Func keySelector!!, IComparer? comparer) + this ParallelQuery source, Func keySelector, IComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( new SortQueryOperator(source, keySelector, comparer, false)); } @@ -1043,8 +1115,11 @@ public static OrderedParallelQuery OrderBy( /// or is a null reference (Nothing in Visual Basic). /// public static OrderedParallelQuery OrderByDescending( - this ParallelQuery source!!, Func keySelector!!) + this ParallelQuery source, Func keySelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery(new SortQueryOperator(source, keySelector, null, true)); } @@ -1067,8 +1142,11 @@ public static OrderedParallelQuery OrderByDescending( /// or is a null reference (Nothing in Visual Basic). /// public static OrderedParallelQuery OrderByDescending( - this ParallelQuery source!!, Func keySelector!!, IComparer? comparer) + this ParallelQuery source, Func keySelector, IComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( new SortQueryOperator(source, keySelector, comparer, true)); } @@ -1094,8 +1172,11 @@ public static OrderedParallelQuery OrderByDescending( /// public static OrderedParallelQuery ThenBy( - this OrderedParallelQuery source!!, Func keySelector!!) + this OrderedParallelQuery source, Func keySelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, null, false)); } @@ -1122,8 +1203,11 @@ public static OrderedParallelQuery ThenBy( /// public static OrderedParallelQuery ThenBy( - this OrderedParallelQuery source!!, Func keySelector!!, IComparer? comparer) + this OrderedParallelQuery source, Func keySelector, IComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, comparer, false)); } @@ -1149,8 +1233,11 @@ public static OrderedParallelQuery ThenBy( /// public static OrderedParallelQuery ThenByDescending( - this OrderedParallelQuery source!!, Func keySelector!!) + this OrderedParallelQuery source, Func keySelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, null, true)); } @@ -1177,8 +1264,11 @@ public static OrderedParallelQuery ThenByDescending( /// public static OrderedParallelQuery ThenByDescending( - this OrderedParallelQuery source!!, Func keySelector!!, IComparer? comparer) + this OrderedParallelQuery source, Func keySelector, IComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, comparer, true)); } @@ -1221,8 +1311,11 @@ public static ParallelQuery> GroupBy( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery> GroupBy( - this ParallelQuery source!!, Func keySelector!!, IEqualityComparer? comparer) + this ParallelQuery source, Func keySelector, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + return new GroupByQueryOperator(source, keySelector, null, comparer); } @@ -1271,8 +1364,12 @@ public static ParallelQuery> GroupBy is a null reference (Nothing in Visual Basic). /// public static ParallelQuery> GroupBy( - this ParallelQuery source!!, Func keySelector!!, Func elementSelector!!, IEqualityComparer? comparer) + this ParallelQuery source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + return new GroupByQueryOperator(source, keySelector, elementSelector, comparer); } @@ -1306,9 +1403,11 @@ public static ParallelQuery> GroupBy is a null reference (Nothing in Visual Basic). /// public static ParallelQuery GroupBy( - this ParallelQuery source, Func keySelector, Func, TResult> resultSelector!!) + this ParallelQuery source, Func keySelector, Func, TResult> resultSelector) { + ArgumentNullException.ThrowIfNull(resultSelector); + return source.GroupBy(keySelector) .Select, TResult>(delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1332,8 +1431,10 @@ public static ParallelQuery GroupBy( /// is a null reference (Nothing in Visual Basic). /// public static ParallelQuery GroupBy( - this ParallelQuery source, Func keySelector, Func, TResult> resultSelector!!, IEqualityComparer? comparer) + this ParallelQuery source, Func keySelector, Func, TResult> resultSelector, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(resultSelector); + return source.GroupBy(keySelector, comparer).Select, TResult>( delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1360,8 +1461,10 @@ public static ParallelQuery GroupBy( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery GroupBy( - this ParallelQuery source, Func keySelector, Func elementSelector, Func, TResult> resultSelector!!) + this ParallelQuery source, Func keySelector, Func elementSelector, Func, TResult> resultSelector) { + ArgumentNullException.ThrowIfNull(resultSelector); + return source.GroupBy(keySelector, elementSelector) .Select, TResult>(delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1389,8 +1492,10 @@ public static ParallelQuery GroupBy( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery GroupBy( - this ParallelQuery source, Func keySelector, Func elementSelector, Func, TResult> resultSelector!!, IEqualityComparer? comparer) + this ParallelQuery source, Func keySelector, Func elementSelector, Func, TResult> resultSelector, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(resultSelector); + return source.GroupBy(keySelector, elementSelector, comparer) .Select, TResult>(delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1508,8 +1613,11 @@ public static TSource Aggregate( } internal static TSource Aggregate( - this ParallelQuery source!!, Func func!!, QueryAggregationOptions options) + this ParallelQuery source, Func func, QueryAggregationOptions options) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + if ((~(QueryAggregationOptions.Associative | QueryAggregationOptions.Commutative) & options) != 0) throw new ArgumentOutOfRangeException(nameof(options)); if ((options & QueryAggregationOptions.Associative) != QueryAggregationOptions.Associative) @@ -1553,8 +1661,11 @@ public static TAccumulate Aggregate( } internal static TAccumulate Aggregate( - this ParallelQuery source!!, TAccumulate seed, Func func!!, QueryAggregationOptions options) + this ParallelQuery source, TAccumulate seed, Func func, QueryAggregationOptions options) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + if ((~(QueryAggregationOptions.Associative | QueryAggregationOptions.Commutative) & options) != 0) throw new ArgumentOutOfRangeException(nameof(options)); return source.PerformSequentialAggregation(seed, true, func); @@ -1584,9 +1695,13 @@ internal static TAccumulate Aggregate( /// The query was canceled. /// public static TResult Aggregate( - this ParallelQuery source!!, TAccumulate seed, Func func!!, - Func resultSelector!!) + this ParallelQuery source, TAccumulate seed, Func func, + Func resultSelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(resultSelector); + TAccumulate acc = source.PerformSequentialAggregation(seed, true, func); try { @@ -1636,9 +1751,14 @@ public static TResult Aggregate( /// The query was canceled. /// public static TResult Aggregate( - this ParallelQuery source!!, TAccumulate seed, Func updateAccumulatorFunc!!, - Func combineAccumulatorsFunc!!, Func resultSelector!!) + this ParallelQuery source, TAccumulate seed, Func updateAccumulatorFunc, + Func combineAccumulatorsFunc, Func resultSelector) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(updateAccumulatorFunc); + ArgumentNullException.ThrowIfNull(combineAccumulatorsFunc); + ArgumentNullException.ThrowIfNull(resultSelector); + return new AssociativeAggregationOperator( source, seed, null, true, updateAccumulatorFunc, combineAccumulatorsFunc, resultSelector, false, QueryAggregationOptions.AssociativeCommutative).Aggregate(); @@ -1684,12 +1804,18 @@ public static TResult Aggregate( /// The query was canceled. /// public static TResult Aggregate( - this ParallelQuery source!!, - Func seedFactory!!, - Func updateAccumulatorFunc!!, - Func combineAccumulatorsFunc!!, - Func resultSelector!!) - { + this ParallelQuery source, + Func seedFactory, + Func updateAccumulatorFunc, + Func combineAccumulatorsFunc, + Func resultSelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(seedFactory); + ArgumentNullException.ThrowIfNull(updateAccumulatorFunc); + ArgumentNullException.ThrowIfNull(combineAccumulatorsFunc); + ArgumentNullException.ThrowIfNull(resultSelector); + return new AssociativeAggregationOperator( source, default!, seedFactory, true, updateAccumulatorFunc, combineAccumulatorsFunc, resultSelector, false, QueryAggregationOptions.AssociativeCommutative).Aggregate(); @@ -1717,8 +1843,10 @@ public static TResult Aggregate( /// /// The query was canceled. /// - public static int Count(this ParallelQuery source!!) + public static int Count(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // If the data source is a collection, we can just return the count right away. if (source is ParallelEnumerableWrapper sourceAsWrapper) { @@ -1757,8 +1885,11 @@ public static int Count(this ParallelQuery source!!) /// /// The query was canceled. /// - public static int Count(this ParallelQuery source!!, Func predicate!!) + public static int Count(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + // Construct a where operator to filter out non-matching elements, and then aggregate. checked { @@ -1783,8 +1914,10 @@ public static int Count(this ParallelQuery source!!, Func /// The query was canceled. /// - public static long LongCount(this ParallelQuery source!!) + public static long LongCount(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // If the data source is a collection, we can just return the count right away. if (source is ParallelEnumerableWrapper sourceAsWrapper) { @@ -1819,8 +1952,11 @@ public static long LongCount(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long LongCount(this ParallelQuery source!!, Func predicate!!) + public static long LongCount(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + // Construct a where operator to filter out non-matching elements, and then aggregate. return new LongCountAggregationOperator(Where(source, predicate)).Aggregate(); } @@ -1845,8 +1981,10 @@ public static long LongCount(this ParallelQuery source!!, Func /// /// The query was canceled. /// - public static int Sum(this ParallelQuery source!!) + public static int Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new IntSumAggregationOperator(source).Aggregate(); } @@ -1866,8 +2004,10 @@ public static int Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static int? Sum(this ParallelQuery source!!) + public static int? Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableIntSumAggregationOperator(source).Aggregate(); } @@ -1887,8 +2027,10 @@ public static int Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long Sum(this ParallelQuery source!!) + public static long Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new LongSumAggregationOperator(source).Aggregate(); } @@ -1908,8 +2050,10 @@ public static long Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long? Sum(this ParallelQuery source!!) + public static long? Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableLongSumAggregationOperator(source).Aggregate(); } @@ -1927,8 +2071,10 @@ public static long Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float Sum(this ParallelQuery source!!) + public static float Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new FloatSumAggregationOperator(source).Aggregate(); } @@ -1946,8 +2092,10 @@ public static float Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float? Sum(this ParallelQuery source!!) + public static float? Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableFloatSumAggregationOperator(source).Aggregate(); } @@ -1965,8 +2113,10 @@ public static float Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double Sum(this ParallelQuery source!!) + public static double Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DoubleSumAggregationOperator(source).Aggregate(); } @@ -1984,8 +2134,10 @@ public static double Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double? Sum(this ParallelQuery source!!) + public static double? Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDoubleSumAggregationOperator(source).Aggregate(); } @@ -2005,8 +2157,10 @@ public static double Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal Sum(this ParallelQuery source!!) + public static decimal Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DecimalSumAggregationOperator(source).Aggregate(); } @@ -2026,8 +2180,10 @@ public static decimal Sum(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal? Sum(this ParallelQuery source!!) + public static decimal? Sum(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDecimalSumAggregationOperator(source).Aggregate(); } @@ -2293,8 +2449,10 @@ public static decimal Sum(this ParallelQuery source, Func /// The query was canceled. /// - public static int Min(this ParallelQuery source!!) + public static int Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new IntMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2312,8 +2470,10 @@ public static int Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static int? Min(this ParallelQuery source!!) + public static int? Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableIntMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2334,8 +2494,10 @@ public static int Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long Min(this ParallelQuery source!!) + public static long Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new LongMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2353,8 +2515,10 @@ public static long Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long? Min(this ParallelQuery source!!) + public static long? Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableLongMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2375,8 +2539,10 @@ public static long Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float Min(this ParallelQuery source!!) + public static float Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new FloatMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2394,8 +2560,10 @@ public static float Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float? Min(this ParallelQuery source!!) + public static float? Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableFloatMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2416,8 +2584,10 @@ public static float Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double Min(this ParallelQuery source!!) + public static double Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DoubleMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2435,8 +2605,10 @@ public static double Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double? Min(this ParallelQuery source!!) + public static double? Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDoubleMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2457,8 +2629,10 @@ public static double Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal Min(this ParallelQuery source!!) + public static decimal Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DecimalMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2476,8 +2650,10 @@ public static decimal Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal? Min(this ParallelQuery source!!) + public static decimal? Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDecimalMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2499,8 +2675,10 @@ public static decimal Min(this ParallelQuery source!!) /// /// The query was canceled. /// - public static TSource? Min(this ParallelQuery source!!) + public static TSource? Min(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return AggregationMinMaxHelpers.ReduceMin(source); } @@ -2786,8 +2964,10 @@ public static decimal Min(this ParallelQuery source, Func /// The query was canceled. /// - public static int Max(this ParallelQuery source!!) + public static int Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new IntMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2805,8 +2985,10 @@ public static int Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static int? Max(this ParallelQuery source!!) + public static int? Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableIntMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2827,8 +3009,10 @@ public static int Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long Max(this ParallelQuery source!!) + public static long Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new LongMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2846,8 +3030,10 @@ public static long Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static long? Max(this ParallelQuery source!!) + public static long? Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableLongMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2868,8 +3054,10 @@ public static long Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float Max(this ParallelQuery source!!) + public static float Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new FloatMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2887,8 +3075,10 @@ public static float Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float? Max(this ParallelQuery source!!) + public static float? Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableFloatMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2909,8 +3099,10 @@ public static float Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double Max(this ParallelQuery source!!) + public static double Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DoubleMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2928,8 +3120,10 @@ public static double Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double? Max(this ParallelQuery source!!) + public static double? Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDoubleMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2950,8 +3144,10 @@ public static double Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal Max(this ParallelQuery source!!) + public static decimal Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DecimalMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2969,8 +3165,10 @@ public static decimal Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal? Max(this ParallelQuery source!!) + public static decimal? Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDecimalMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2991,8 +3189,10 @@ public static decimal Max(this ParallelQuery source!!) /// /// The query was canceled. /// - public static TSource? Max(this ParallelQuery source!!) + public static TSource? Max(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return AggregationMinMaxHelpers.ReduceMax(source); } @@ -3280,8 +3480,10 @@ public static decimal Max(this ParallelQuery source, Func /// The query was canceled. /// - public static double Average(this ParallelQuery source!!) + public static double Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new IntAverageAggregationOperator(source).Aggregate(); } @@ -3301,8 +3503,10 @@ public static double Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double? Average(this ParallelQuery source!!) + public static double? Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableIntAverageAggregationOperator(source).Aggregate(); } @@ -3325,8 +3529,10 @@ public static double Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double Average(this ParallelQuery source!!) + public static double Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new LongAverageAggregationOperator(source).Aggregate(); } @@ -3346,8 +3552,10 @@ public static double Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double? Average(this ParallelQuery source!!) + public static double? Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableLongAverageAggregationOperator(source).Aggregate(); } @@ -3368,8 +3576,10 @@ public static double Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float Average(this ParallelQuery source!!) + public static float Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new FloatAverageAggregationOperator(source).Aggregate(); } @@ -3387,8 +3597,10 @@ public static float Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static float? Average(this ParallelQuery source!!) + public static float? Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableFloatAverageAggregationOperator(source).Aggregate(); } @@ -3409,8 +3621,10 @@ public static float Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double Average(this ParallelQuery source!!) + public static double Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DoubleAverageAggregationOperator(source).Aggregate(); } @@ -3428,8 +3642,10 @@ public static double Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static double? Average(this ParallelQuery source!!) + public static double? Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDoubleAverageAggregationOperator(source).Aggregate(); } @@ -3450,8 +3666,10 @@ public static double Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal Average(this ParallelQuery source!!) + public static decimal Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new DecimalAverageAggregationOperator(source).Aggregate(); } @@ -3469,8 +3687,10 @@ public static decimal Average(this ParallelQuery source!!) /// /// The query was canceled. /// - public static decimal? Average(this ParallelQuery source!!) + public static decimal? Average(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new NullableDecimalAverageAggregationOperator(source).Aggregate(); } @@ -3739,8 +3959,11 @@ public static decimal Average(this ParallelQuery source, Func< /// /// The query was canceled. /// - public static bool Any(this ParallelQuery source!!, Func predicate!!) + public static bool Any(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new AnyAllSearchOperator(source, true, predicate).Aggregate(); } @@ -3759,8 +3982,10 @@ public static bool Any(this ParallelQuery source!!, Func /// The query was canceled. /// - public static bool Any(this ParallelQuery source!!) + public static bool Any(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return Any(source, x => true); } @@ -3786,8 +4011,11 @@ public static bool Any(this ParallelQuery source!!) /// /// The query was canceled. /// - public static bool All(this ParallelQuery source!!, Func predicate!!) + public static bool All(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new AnyAllSearchOperator(source, false, predicate).Aggregate(); } @@ -3839,8 +4067,10 @@ public static bool Contains(this ParallelQuery source, TSource /// /// The query was canceled. /// - public static bool Contains(this ParallelQuery source!!, TSource value, IEqualityComparer? comparer) + public static bool Contains(this ParallelQuery source, TSource value, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: there are many simple optimizations we can make for collection types with known sizes. return new ContainsSearchOperator(source, value, comparer).Aggregate(); @@ -3866,8 +4096,10 @@ public static bool Contains(this ParallelQuery source!!, TSour /// /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Take(this ParallelQuery source!!, int count) + public static ParallelQuery Take(this ParallelQuery source, int count) { + ArgumentNullException.ThrowIfNull(source); + if (count > 0) { return new TakeOrSkipQueryOperator(source, count, true); @@ -3896,8 +4128,11 @@ public static ParallelQuery Take(this ParallelQuery s /// /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery TakeWhile(this ParallelQuery source!!, Func predicate!!) + public static ParallelQuery TakeWhile(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new TakeOrSkipWhileQueryOperator(source, predicate, null, true); } @@ -3918,8 +4153,11 @@ public static ParallelQuery TakeWhile(this ParallelQuery /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery TakeWhile(this ParallelQuery source!!, Func predicate!!) + public static ParallelQuery TakeWhile(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new TakeOrSkipWhileQueryOperator(source, null, predicate, true); } @@ -3940,8 +4178,10 @@ public static ParallelQuery TakeWhile(this ParallelQuery /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Skip(this ParallelQuery source!!, int count) + public static ParallelQuery Skip(this ParallelQuery source, int count) { + ArgumentNullException.ThrowIfNull(source); + // If the count is 0 (or less) we just return the whole stream. if (count <= 0) { @@ -3970,8 +4210,11 @@ public static ParallelQuery Skip(this ParallelQuery s /// /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery SkipWhile(this ParallelQuery source!!, Func predicate!!) + public static ParallelQuery SkipWhile(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new TakeOrSkipWhileQueryOperator(source, predicate, null, false); } @@ -3994,8 +4237,11 @@ public static ParallelQuery SkipWhile(this ParallelQuery /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery SkipWhile(this ParallelQuery source!!, Func predicate!!) + public static ParallelQuery SkipWhile(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return new TakeOrSkipWhileQueryOperator(source, null, predicate, false); } @@ -4017,8 +4263,11 @@ public static ParallelQuery SkipWhile(this ParallelQuery /// or is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Concat(this ParallelQuery first!!, ParallelQuery second!!) + public static ParallelQuery Concat(this ParallelQuery first, ParallelQuery second) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + return new ConcatQueryOperator(first, second); } @@ -4067,8 +4316,11 @@ public static ParallelQuery Concat(this ParallelQuery /// /// The query was canceled. /// - public static bool SequenceEqual(this ParallelQuery first!!, ParallelQuery second!!) + public static bool SequenceEqual(this ParallelQuery first, ParallelQuery second) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + return SequenceEqual(first, second, null); } @@ -4114,8 +4366,11 @@ public static bool SequenceEqual(this ParallelQuery first, IEn /// /// The query was canceled. /// - public static bool SequenceEqual(this ParallelQuery first!!, ParallelQuery second!!, IEqualityComparer? comparer) + public static bool SequenceEqual(this ParallelQuery first, ParallelQuery second, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + // If comparer is null, use the default one comparer ??= EqualityComparer.Default; @@ -4229,8 +4484,10 @@ public static ParallelQuery Distinct( /// is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Distinct( - this ParallelQuery source!!, IEqualityComparer? comparer) + this ParallelQuery source, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(source); + return new DistinctQueryOperator(source, comparer); } @@ -4288,8 +4545,11 @@ public static ParallelQuery Union( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Union( - this ParallelQuery first!!, ParallelQuery second!!, IEqualityComparer? comparer) + this ParallelQuery first, ParallelQuery second, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + return new UnionQueryOperator(first, second, comparer); } @@ -4380,8 +4640,11 @@ public static ParallelQuery Intersect( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Intersect( - this ParallelQuery first!!, ParallelQuery second!!, IEqualityComparer? comparer) + this ParallelQuery first, ParallelQuery second, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + return new IntersectQueryOperator(first, second, comparer); } @@ -4473,8 +4736,11 @@ public static ParallelQuery Except( /// or is a null reference (Nothing in Visual Basic). /// public static ParallelQuery Except( - this ParallelQuery first!!, ParallelQuery second!!, IEqualityComparer? comparer) + this ParallelQuery first, ParallelQuery second, IEqualityComparer? comparer) { + ArgumentNullException.ThrowIfNull(first); + ArgumentNullException.ThrowIfNull(second); + return new ExceptQueryOperator(first, second, comparer); } @@ -4545,8 +4811,10 @@ public static IEnumerable AsEnumerable(this ParallelQuery /// The query was canceled. /// - public static TSource[] ToArray(this ParallelQuery source!!) + public static TSource[] ToArray(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + if (source is QueryOperator asOperator) { return asOperator.ExecuteAndGetResultsAsArray(); @@ -4575,8 +4843,10 @@ public static TSource[] ToArray(this ParallelQuery source!!) /// /// The query was canceled. /// - public static List ToList(this ParallelQuery source!!) + public static List ToList(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // Allocate a growable list (optionally passing the length as the initial size). List list = new List(); IEnumerator input; @@ -4684,8 +4954,11 @@ public static Dictionary ToDictionary( /// The query was canceled. /// public static Dictionary ToDictionary( - this ParallelQuery source!!, Func keySelector!!, IEqualityComparer? comparer) where TKey : notnull + this ParallelQuery source, Func keySelector, IEqualityComparer? comparer) where TKey : notnull { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary result = new Dictionary(comparer); @@ -4778,8 +5051,12 @@ public static Dictionary ToDictionary( /// The query was canceled. /// public static Dictionary ToDictionary( - this ParallelQuery source!!, Func keySelector!!, Func elementSelector!!, IEqualityComparer? comparer) where TKey : notnull + this ParallelQuery source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) where TKey : notnull { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary result = new Dictionary(comparer); @@ -4856,8 +5133,11 @@ public static ILookup ToLookup( /// The query was canceled. /// public static ILookup ToLookup( - this ParallelQuery source!!, Func keySelector!!, IEqualityComparer? comparer) where TKey: notnull + this ParallelQuery source, Func keySelector, IEqualityComparer? comparer) where TKey: notnull { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + // comparer may be null, in which case we use the default comparer. comparer = comparer ?? EqualityComparer.Default; @@ -4939,8 +5219,12 @@ public static ILookup ToLookup( /// The query was canceled. /// public static ILookup ToLookup( - this ParallelQuery source!!, Func keySelector!!, Func elementSelector!!, IEqualityComparer? comparer) where TKey : notnull + this ParallelQuery source, Func keySelector, Func elementSelector, IEqualityComparer? comparer) where TKey : notnull { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + // comparer may be null, in which case we use the default comparer. comparer = comparer ?? EqualityComparer.Default; @@ -4981,8 +5265,10 @@ public static ILookup ToLookup( /// /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Reverse(this ParallelQuery source!!) + public static ParallelQuery Reverse(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return new ReverseQueryOperator(source); } @@ -5001,8 +5287,10 @@ public static ParallelQuery Reverse(this ParallelQuery /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery OfType(this ParallelQuery source!!) + public static ParallelQuery OfType(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return source.OfType(); } @@ -5017,8 +5305,10 @@ public static ParallelQuery OfType(this ParallelQuery source!! /// /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery Cast(this ParallelQuery source!!) + public static ParallelQuery Cast(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + return source.Cast(); } @@ -5100,8 +5390,10 @@ public static ParallelQuery Cast(this ParallelQuery source!!) /// /// The query was canceled. /// - public static TSource First(this ParallelQuery source!!) + public static TSource First(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the 0th element. FirstQueryOperator queryOp = new FirstQueryOperator(source, null); @@ -5141,8 +5433,11 @@ public static TSource First(this ParallelQuery source!!) /// /// The query was canceled. /// - public static TSource First(this ParallelQuery source!!, Func predicate!!) + public static TSource First(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + FirstQueryOperator queryOp = new FirstQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5177,8 +5472,10 @@ public static TSource First(this ParallelQuery source!!, Func< /// /// The query was canceled. /// - public static TSource? FirstOrDefault(this ParallelQuery source!!) + public static TSource? FirstOrDefault(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the 0th element. FirstQueryOperator queryOp = new FirstQueryOperator(source, null); @@ -5221,8 +5518,11 @@ public static TSource First(this ParallelQuery source!!, Func< /// /// The query was canceled. /// - public static TSource? FirstOrDefault(this ParallelQuery source!!, Func predicate!!) + public static TSource? FirstOrDefault(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + FirstQueryOperator queryOp = new FirstQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5266,8 +5566,10 @@ public static TSource First(this ParallelQuery source!!, Func< /// /// The query was canceled. /// - public static TSource Last(this ParallelQuery source!!) + public static TSource Last(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the last element. LastQueryOperator queryOp = new LastQueryOperator(source, null); @@ -5307,8 +5609,11 @@ public static TSource Last(this ParallelQuery source!!) /// /// The query was canceled. /// - public static TSource Last(this ParallelQuery source!!, Func predicate!!) + public static TSource Last(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + LastQueryOperator queryOp = new LastQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5345,8 +5650,10 @@ public static TSource Last(this ParallelQuery source!!, Func /// The query was canceled. /// - public static TSource? LastOrDefault(this ParallelQuery source!!) + public static TSource? LastOrDefault(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the last element. LastQueryOperator queryOp = new LastQueryOperator(source, null); @@ -5385,8 +5692,11 @@ public static TSource Last(this ParallelQuery source!!, Func /// The query was canceled. /// - public static TSource? LastOrDefault(this ParallelQuery source!!, Func predicate!!) + public static TSource? LastOrDefault(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + LastQueryOperator queryOp = new LastQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5430,8 +5740,10 @@ public static TSource Last(this ParallelQuery source!!, Func /// The query was canceled. /// - public static TSource Single(this ParallelQuery source!!) + public static TSource Single(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: optimize for ICollection-typed data sources, i.e. we can just // check the Count property and avoid costly fork/join/synchronization. return GetOneWithPossibleDefault(new SingleQueryOperator(source, null), true, false)!; @@ -5457,8 +5769,11 @@ public static TSource Single(this ParallelQuery source!!) /// /// The query was canceled. /// - public static TSource Single(this ParallelQuery source!!, Func predicate!!) + public static TSource Single(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return GetOneWithPossibleDefault(new SingleQueryOperator(source, predicate), true, false)!; } @@ -5481,8 +5796,10 @@ public static TSource Single(this ParallelQuery source!!, Func /// /// The query was canceled. /// - public static TSource? SingleOrDefault(this ParallelQuery source!!) + public static TSource? SingleOrDefault(this ParallelQuery source) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: optimize for ICollection-typed data sources, i.e. we can just // check the Count property and avoid costly fork/join/synchronization. return GetOneWithPossibleDefault(new SingleQueryOperator(source, null), true, true); @@ -5509,8 +5826,11 @@ public static TSource Single(this ParallelQuery source!!, Func /// /// The query was canceled. /// - public static TSource? SingleOrDefault(this ParallelQuery source!!, Func predicate!!) + public static TSource? SingleOrDefault(this ParallelQuery source, Func predicate) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + return GetOneWithPossibleDefault(new SingleQueryOperator(source, predicate), true, true); } @@ -5549,8 +5869,10 @@ public static TSource Single(this ParallelQuery source!!, Func /// /// is a null reference (Nothing in Visual Basic). /// - public static ParallelQuery DefaultIfEmpty(this ParallelQuery source!!, TSource defaultValue) + public static ParallelQuery DefaultIfEmpty(this ParallelQuery source, TSource defaultValue) { + ArgumentNullException.ThrowIfNull(source); + return new DefaultIfEmptyQueryOperator(source, defaultValue); } @@ -5579,8 +5901,10 @@ public static ParallelQuery DefaultIfEmpty(this ParallelQuery< /// /// The query was canceled. /// - public static TSource ElementAt(this ParallelQuery source!!, int index) + public static TSource ElementAt(this ParallelQuery source, int index) { + ArgumentNullException.ThrowIfNull(source); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); // @PERF: there are obvious optimization opportunities for indexable data sources, @@ -5617,8 +5941,10 @@ public static TSource ElementAt(this ParallelQuery source!!, i /// /// The query was canceled. /// - public static TSource? ElementAtOrDefault(this ParallelQuery source!!, int index) + public static TSource? ElementAtOrDefault(this ParallelQuery source, int index) { + ArgumentNullException.ThrowIfNull(source); + // @PERF: there are obvious optimization opportunities for indexable data sources, // since we can just seek to the element requested. diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs index 9665e62bfaa960..97c4b0daeb75c3 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/EnumerableQuery.cs @@ -60,8 +60,10 @@ public EnumerableQuery(Expression expression) [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")] - IQueryable IQueryProvider.CreateQuery(Expression expression!!) + IQueryable IQueryProvider.CreateQuery(Expression expression) { + ArgumentNullException.ThrowIfNull(expression); + Type? iqType = TypeHelper.FindGenericType(typeof(IQueryable<>), expression.Type); if (iqType == null) throw Error.ArgumentNotValid(nameof(expression)); @@ -70,8 +72,10 @@ IQueryable IQueryProvider.CreateQuery(Expression expression!!) [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")] - IQueryable IQueryProvider.CreateQuery(Expression expression!!) + IQueryable IQueryProvider.CreateQuery(Expression expression) { + ArgumentNullException.ThrowIfNull(expression); + if (!typeof(IQueryable).IsAssignableFrom(expression.Type)) { throw Error.ArgumentNotValid(nameof(expression)); @@ -81,15 +85,19 @@ IQueryable IQueryProvider.CreateQuery(Expression expression! [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")] - object? IQueryProvider.Execute(Expression expression!!) + object? IQueryProvider.Execute(Expression expression) { + ArgumentNullException.ThrowIfNull(expression); + return EnumerableExecutor.Create(expression).ExecuteBoxed(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This class's ctor is annotated as RequiresUnreferencedCode.")] - TElement IQueryProvider.Execute(Expression expression!!) + TElement IQueryProvider.Execute(Expression expression) { + ArgumentNullException.ThrowIfNull(expression); + if (!typeof(TElement).IsAssignableFrom(expression.Type)) throw Error.ArgumentNotValid(nameof(expression)); return new EnumerableExecutor(expression).Execute(); diff --git a/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs b/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs index 9dc67e586f9fe7..4da403980f3874 100644 --- a/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs +++ b/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs @@ -13,12 +13,18 @@ public static class Queryable internal const string InMemoryQueryableExtensionMethodsRequiresUnreferencedCode = "Enumerating in-memory collections as IQueryable can require unreferenced code because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods. The IEnumerable extension methods could be trimmed causing the application to fail at runtime."; [RequiresUnreferencedCode(InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)] - public static IQueryable AsQueryable(this IEnumerable source!!) => - source as IQueryable ?? new EnumerableQuery(source); + public static IQueryable AsQueryable(this IEnumerable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source as IQueryable ?? new EnumerableQuery(source); + } [RequiresUnreferencedCode(InMemoryQueryableExtensionMethodsRequiresUnreferencedCode)] - public static IQueryable AsQueryable(this IEnumerable source!!) + public static IQueryable AsQueryable(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + if (source is IQueryable queryable) { return queryable; @@ -34,90 +40,140 @@ public static IQueryable AsQueryable(this IEnumerable source!!) } [DynamicDependency("Where`1", typeof(Enumerable))] - public static IQueryable Where(this IQueryable source!!, Expression> predicate!!) => - source.Provider.CreateQuery( + public static IQueryable Where(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Where_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("Where`1", typeof(Enumerable))] - public static IQueryable Where(this IQueryable source!!, Expression> predicate!!) => - source.Provider.CreateQuery( + public static IQueryable Where(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Where_Index_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("OfType`1", typeof(Enumerable))] - public static IQueryable OfType(this IQueryable source!!) => - source.Provider.CreateQuery( + public static IQueryable OfType(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.OfType_TResult_1(typeof(TResult)), source.Expression)); + } [DynamicDependency("Cast`1", typeof(Enumerable))] - public static IQueryable Cast(this IQueryable source!!) => - source.Provider.CreateQuery( + public static IQueryable Cast(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Cast_TResult_1(typeof(TResult)), source.Expression)); + } [DynamicDependency("Select`2", typeof(Enumerable))] - public static IQueryable Select(this IQueryable source!!, Expression> selector!!) => - source.Provider.CreateQuery( + public static IQueryable Select(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Select_TSource_TResult_2(typeof(TSource), typeof(TResult)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Select`2", typeof(Enumerable))] - public static IQueryable Select(this IQueryable source!!, Expression> selector!!) => - source.Provider.CreateQuery( + public static IQueryable Select(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Select_Index_TSource_TResult_2(typeof(TSource), typeof(TResult)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("SelectMany`2", typeof(Enumerable))] - public static IQueryable SelectMany(this IQueryable source!!, Expression>> selector!!) => - source.Provider.CreateQuery( + public static IQueryable SelectMany(this IQueryable source, Expression>> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SelectMany_TSource_TResult_2(typeof(TSource), typeof(TResult)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("SelectMany`2", typeof(Enumerable))] - public static IQueryable SelectMany(this IQueryable source!!, Expression>> selector!!) => - source.Provider.CreateQuery( + public static IQueryable SelectMany(this IQueryable source, Expression>> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SelectMany_Index_TSource_TResult_2(typeof(TSource), typeof(TResult)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("SelectMany`3", typeof(Enumerable))] - public static IQueryable SelectMany(this IQueryable source!!, Expression>> collectionSelector!!, Expression> resultSelector!!) => - source.Provider.CreateQuery( + public static IQueryable SelectMany(this IQueryable source, Expression>> collectionSelector, Expression> resultSelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SelectMany_Index_TSource_TCollection_TResult_3(typeof(TSource), typeof(TCollection), typeof(TResult)), source.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) )); + } [DynamicDependency("SelectMany`3", typeof(Enumerable))] - public static IQueryable SelectMany(this IQueryable source!!, Expression>> collectionSelector!!, Expression> resultSelector!!) => - source.Provider.CreateQuery( + public static IQueryable SelectMany(this IQueryable source, Expression>> collectionSelector, Expression> resultSelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionSelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SelectMany_TSource_TCollection_TResult_3(typeof(TSource), typeof(TCollection), typeof(TResult)), source.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) )); + } private static Expression GetSourceExpression(IEnumerable source) { @@ -126,101 +182,189 @@ private static Expression GetSourceExpression(IEnumerable sour } [DynamicDependency("Join`4", typeof(Enumerable))] - public static IQueryable Join(this IQueryable outer!!, IEnumerable inner!!, Expression> outerKeySelector!!, Expression> innerKeySelector!!, Expression> resultSelector!!) => outer.Provider.CreateQuery( + public static IQueryable Join(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector) + { + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return outer.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Join_TOuter_TInner_TKey_TResult_5(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)), outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector))); + } [DynamicDependency("Join`4", typeof(Enumerable))] - public static IQueryable Join(this IQueryable outer!!, IEnumerable inner!!, Expression> outerKeySelector!!, Expression> innerKeySelector!!, Expression> resultSelector!!, IEqualityComparer? comparer) => outer.Provider.CreateQuery( + public static IQueryable Join(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return outer.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Join_TOuter_TInner_TKey_TResult_6(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)), outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer)))); + } [DynamicDependency("GroupJoin`4", typeof(Enumerable))] - public static IQueryable GroupJoin(this IQueryable outer!!, IEnumerable inner!!, Expression> outerKeySelector!!, Expression> innerKeySelector!!, Expression, TResult>> resultSelector!!) => outer.Provider.CreateQuery( + public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector) + { + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return outer.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.GroupJoin_TOuter_TInner_TKey_TResult_5(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)), outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector))); + } [DynamicDependency("GroupJoin`4", typeof(Enumerable))] - public static IQueryable GroupJoin(this IQueryable outer!!, IEnumerable inner!!, Expression> outerKeySelector!!, Expression> innerKeySelector!!, Expression, TResult>> resultSelector!!, IEqualityComparer? comparer) => outer.Provider.CreateQuery( + public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(outer); + ArgumentNullException.ThrowIfNull(inner); + ArgumentNullException.ThrowIfNull(outerKeySelector); + ArgumentNullException.ThrowIfNull(innerKeySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return outer.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.GroupJoin_TOuter_TInner_TKey_TResult_6(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)), outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer)))); + } [DynamicDependency("OrderBy`2", typeof(Enumerable))] - public static IOrderedQueryable OrderBy(this IQueryable source!!, Expression> keySelector!!) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable OrderBy(this IQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.OrderBy_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } [DynamicDependency("OrderBy`2", typeof(Enumerable))] - public static IOrderedQueryable OrderBy(this IQueryable source!!, Expression> keySelector!!, IComparer? comparer) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable OrderBy(this IQueryable source, Expression> keySelector, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.OrderBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("OrderByDescending`2", typeof(Enumerable))] - public static IOrderedQueryable OrderByDescending(this IQueryable source!!, Expression> keySelector!!) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable OrderByDescending(this IQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.OrderByDescending_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } [DynamicDependency("OrderByDescending`2", typeof(Enumerable))] - public static IOrderedQueryable OrderByDescending(this IQueryable source!!, Expression> keySelector!!, IComparer? comparer) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable OrderByDescending(this IQueryable source, Expression> keySelector, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.OrderByDescending_TSource_TKey_3(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("ThenBy`2", typeof(Enumerable))] - public static IOrderedQueryable ThenBy(this IOrderedQueryable source!!, Expression> keySelector!!) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable ThenBy(this IOrderedQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.ThenBy_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } [DynamicDependency("ThenBy`2", typeof(Enumerable))] - public static IOrderedQueryable ThenBy(this IOrderedQueryable source!!, Expression> keySelector!!, IComparer? comparer) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable ThenBy(this IOrderedQueryable source, Expression> keySelector, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.ThenBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("ThenByDescending`2", typeof(Enumerable))] - public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source!!, Expression> keySelector!!) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.ThenByDescending_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } [DynamicDependency("ThenByDescending`2", typeof(Enumerable))] - public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source!!, Expression> keySelector!!, IComparer? comparer) => (IOrderedQueryable)source.Provider.CreateQuery( + public static IOrderedQueryable ThenByDescending(this IOrderedQueryable source, Expression> keySelector, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return (IOrderedQueryable)source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.ThenByDescending_TSource_TKey_3(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("Take`1", typeof(Enumerable))] - public static IQueryable Take(this IQueryable source!!, int count) => - source.Provider.CreateQuery( + public static IQueryable Take(this IQueryable source, int count) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Take_Int32_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(count) )); + } /// Returns a specified range of contiguous elements from a sequence. /// The type of the elements of . @@ -229,138 +373,222 @@ public static IQueryable Take(this IQueryable source! /// is . /// An that contains the specified of elements from the sequence. [DynamicDependency("Take`1", typeof(Enumerable))] - public static IQueryable Take(this IQueryable source!!, Range range) => - source.Provider.CreateQuery( + public static IQueryable Take(this IQueryable source, Range range) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Take_Range_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(range) )); + } [DynamicDependency("TakeWhile`1", typeof(Enumerable))] - public static IQueryable TakeWhile(this IQueryable source!!, Expression> predicate!!) => - source.Provider.CreateQuery( + public static IQueryable TakeWhile(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.TakeWhile_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("TakeWhile`1", typeof(Enumerable))] - public static IQueryable TakeWhile(this IQueryable source!!, Expression> predicate!!) => - source.Provider.CreateQuery( + public static IQueryable TakeWhile(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.TakeWhile_Index_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("Skip`1", typeof(Enumerable))] - public static IQueryable Skip(this IQueryable source!!, int count) => - source.Provider.CreateQuery( + public static IQueryable Skip(this IQueryable source, int count) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Skip_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(count) )); + } [DynamicDependency("SkipWhile`1", typeof(Enumerable))] - public static IQueryable SkipWhile(this IQueryable source!!, Expression> predicate!!) => - source.Provider.CreateQuery( + public static IQueryable SkipWhile(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SkipWhile_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("SkipWhile`1", typeof(Enumerable))] - public static IQueryable SkipWhile(this IQueryable source!!, Expression> predicate!!) => - source.Provider.CreateQuery( + public static IQueryable SkipWhile(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SkipWhile_Index_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("GroupBy`2", typeof(Enumerable))] - public static IQueryable> GroupBy(this IQueryable source!!, Expression> keySelector!!) => - source.Provider.CreateQuery>( + public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.CreateQuery>( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } [DynamicDependency("GroupBy`3", typeof(Enumerable))] - public static IQueryable> GroupBy(this IQueryable source!!, Expression> keySelector!!, Expression> elementSelector!!) => - source.Provider.CreateQuery>( + public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + + return source.Provider.CreateQuery>( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_TElement_3(typeof(TSource), typeof(TKey), typeof(TElement)), source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector) )); + } [DynamicDependency("GroupBy`2", typeof(Enumerable))] - public static IQueryable> GroupBy(this IQueryable source!!, Expression> keySelector!!, IEqualityComparer? comparer) => - source.Provider.CreateQuery>( + public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.CreateQuery>( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } [DynamicDependency("GroupBy`3", typeof(Enumerable))] - public static IQueryable> GroupBy(this IQueryable source!!, Expression> keySelector!!, Expression> elementSelector!!, IEqualityComparer? comparer) => - source.Provider.CreateQuery>( + public static IQueryable> GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + + return source.Provider.CreateQuery>( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_TElement_4(typeof(TSource), typeof(TKey), typeof(TElement)), source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Constant(comparer, typeof(IEqualityComparer)))); + } [DynamicDependency("GroupBy`4", typeof(Enumerable))] - public static IQueryable GroupBy(this IQueryable source!!, Expression> keySelector!!, Expression> elementSelector!!, Expression, TResult>> resultSelector!!) => - source.Provider.CreateQuery( + public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector, Expression, TResult>> resultSelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_TElement_TResult_4(typeof(TSource), typeof(TKey), typeof(TElement), typeof(TResult)), source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Quote(resultSelector))); + } [DynamicDependency("GroupBy`3", typeof(Enumerable))] - public static IQueryable GroupBy(this IQueryable source!!, Expression> keySelector!!, Expression, TResult>> resultSelector!!) => - source.Provider.CreateQuery( + public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression, TResult>> resultSelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_TResult_3(typeof(TSource), typeof(TKey), typeof(TResult)), source.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector) )); + } [DynamicDependency("GroupBy`3", typeof(Enumerable))] - public static IQueryable GroupBy(this IQueryable source!!, Expression> keySelector!!, Expression, TResult>> resultSelector!!, IEqualityComparer? comparer) => - source.Provider.CreateQuery( + public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression, TResult>> resultSelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_TResult_4(typeof(TSource), typeof(TKey), typeof(TResult)), source.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer)))); + } [DynamicDependency("GroupBy`4", typeof(Enumerable))] - public static IQueryable GroupBy(this IQueryable source!!, Expression> keySelector!!, Expression> elementSelector!!, Expression, TResult>> resultSelector!!, IEqualityComparer? comparer) => - source.Provider.CreateQuery( + public static IQueryable GroupBy(this IQueryable source, Expression> keySelector, Expression> elementSelector, Expression, TResult>> resultSelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + ArgumentNullException.ThrowIfNull(elementSelector); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.GroupBy_TSource_TKey_TElement_TResult_5(typeof(TSource), typeof(TKey), typeof(TElement), typeof(TResult)), source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer)))); + } [DynamicDependency("Distinct`1", typeof(Enumerable))] - public static IQueryable Distinct(this IQueryable source!!) => - source.Provider.CreateQuery( + public static IQueryable Distinct(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Distinct_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("Distinct`1", typeof(Enumerable))] - public static IQueryable Distinct(this IQueryable source!!, IEqualityComparer? comparer) => - source.Provider.CreateQuery( + public static IQueryable Distinct(this IQueryable source, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Distinct_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } /// Returns distinct elements from a sequence according to a specified key selector function. /// The type of the elements of . @@ -370,13 +598,18 @@ public static IQueryable Distinct(this IQueryable sou /// An that contains distinct elements from the source sequence. /// is . [DynamicDependency("DistinctBy`2", typeof(Enumerable))] - public static IQueryable DistinctBy(this IQueryable source!!, Expression> keySelector!!) => - source.Provider.CreateQuery( + public static IQueryable DistinctBy(this IQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.DistinctBy_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } /// Returns distinct elements from a sequence according to a specified key selector function. /// The type of the elements of . @@ -387,13 +620,18 @@ public static IQueryable DistinctBy(this IQueryableAn that contains distinct elements from the source sequence. /// is . [DynamicDependency("DistinctBy`2", typeof(Enumerable))] - public static IQueryable DistinctBy(this IQueryable source!!, Expression> keySelector!!, IEqualityComparer? comparer) => - source.Provider.CreateQuery( + public static IQueryable DistinctBy(this IQueryable source, Expression> keySelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.DistinctBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } /// Split the elements of a sequence into chunks of size at most . /// An whose elements to chunk. @@ -407,39 +645,59 @@ public static IQueryable DistinctBy(this IQueryableThe last chunk will contain the remaining elements and may be of a smaller size. /// [DynamicDependency("Chunk`1", typeof(Enumerable))] - public static IQueryable Chunk(this IQueryable source!!, int size) => - source.Provider.CreateQuery( + public static IQueryable Chunk(this IQueryable source, int size) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Chunk_TSource_1(typeof(TSource)), source.Expression, Expression.Constant(size) )); + } [DynamicDependency("Concat`1", typeof(Enumerable))] - public static IQueryable Concat(this IQueryable source1!!, IEnumerable source2!!) => - source1.Provider.CreateQuery( + public static IQueryable Concat(this IQueryable source1, IEnumerable source2) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Concat_TSource_2(typeof(TSource)), source1.Expression, GetSourceExpression(source2) )); + } [DynamicDependency("Zip`2", typeof(Enumerable))] - public static IQueryable<(TFirst First, TSecond Second)> Zip(this IQueryable source1!!, IEnumerable source2!!) => - source1.Provider.CreateQuery<(TFirst, TSecond)>( + public static IQueryable<(TFirst First, TSecond Second)> Zip(this IQueryable source1, IEnumerable source2) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery<(TFirst, TSecond)>( Expression.Call( null, CachedReflectionInfo.Zip_TFirst_TSecond_2(typeof(TFirst), typeof(TSecond)), source1.Expression, GetSourceExpression(source2))); + } [DynamicDependency("Zip`3", typeof(Enumerable))] - public static IQueryable Zip(this IQueryable source1!!, IEnumerable source2!!, Expression> resultSelector!!) => - source1.Provider.CreateQuery( + public static IQueryable Zip(this IQueryable source1, IEnumerable source2, Expression> resultSelector) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(resultSelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Zip_TFirst_TSecond_TResult_3(typeof(TFirst), typeof(TSecond), typeof(TResult)), source1.Expression, GetSourceExpression(source2), Expression.Quote(resultSelector) )); + } /// /// Produces a sequence of tuples with elements from the three specified sequences. @@ -452,26 +710,41 @@ public static IQueryable Zip(this IQueryable< /// The third sequence to merge. /// A sequence of tuples with elements taken from the first, second and third sequences, in that order. [DynamicDependency("Zip`3", typeof(Enumerable))] - public static IQueryable<(TFirst First, TSecond Second, TThird Third)> Zip(this IQueryable source1!!, IEnumerable source2!!, IEnumerable source3!!) => - source1.Provider.CreateQuery<(TFirst, TSecond, TThird)>( + public static IQueryable<(TFirst First, TSecond Second, TThird Third)> Zip(this IQueryable source1, IEnumerable source2, IEnumerable source3) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(source3); + + return source1.Provider.CreateQuery<(TFirst, TSecond, TThird)>( Expression.Call( null, CachedReflectionInfo.Zip_TFirst_TSecond_TThird_3(typeof(TFirst), typeof(TSecond), typeof(TThird)), source1.Expression, GetSourceExpression(source2), GetSourceExpression(source3) )); + } [DynamicDependency("Union`1", typeof(Enumerable))] - public static IQueryable Union(this IQueryable source1!!, IEnumerable source2!!) => - source1.Provider.CreateQuery( + public static IQueryable Union(this IQueryable source1, IEnumerable source2) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Union_TSource_2(typeof(TSource)), source1.Expression, GetSourceExpression(source2) )); + } [DynamicDependency("Union`1", typeof(Enumerable))] - public static IQueryable Union(this IQueryable source1!!, IEnumerable source2!!, IEqualityComparer? comparer) => - source1.Provider.CreateQuery( + public static IQueryable Union(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Union_TSource_3(typeof(TSource)), @@ -479,6 +752,7 @@ public static IQueryable Union(this IQueryable source GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } /// Produces the set union of two sequences according to a specified key selector function. /// The type of the elements of the input sequences. @@ -489,13 +763,19 @@ public static IQueryable Union(this IQueryable source /// An that contains the elements from both input sequences, excluding duplicates. /// or is . [DynamicDependency("UnionBy`2", typeof(Enumerable))] - public static IQueryable UnionBy(this IQueryable source1!!, IEnumerable source2!!, Expression> keySelector!!) => - source1.Provider.CreateQuery( + public static IQueryable UnionBy(this IQueryable source1, IEnumerable source2, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(keySelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.UnionBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), source1.Expression, GetSourceExpression(source2), Expression.Quote(keySelector) )); + } /// Produces the set union of two sequences according to a specified key selector function. /// The type of the elements of the input sequences. @@ -507,8 +787,13 @@ public static IQueryable UnionBy(this IQueryableAn that contains the elements from both input sequences, excluding duplicates. /// or is . [DynamicDependency("UnionBy`2", typeof(Enumerable))] - public static IQueryable UnionBy(this IQueryable source1!!, IEnumerable source2!!, Expression> keySelector!!, IEqualityComparer? comparer) => - source1.Provider.CreateQuery( + public static IQueryable UnionBy(this IQueryable source1, IEnumerable source2, Expression> keySelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(keySelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.UnionBy_TSource_TKey_4(typeof(TSource), typeof(TKey)), @@ -517,19 +802,29 @@ public static IQueryable UnionBy(this IQueryable)) )); + } [DynamicDependency("Intersect`1", typeof(Enumerable))] - public static IQueryable Intersect(this IQueryable source1!!, IEnumerable source2!!) => - source1.Provider.CreateQuery( + public static IQueryable Intersect(this IQueryable source1, IEnumerable source2) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Intersect_TSource_2(typeof(TSource)), source1.Expression, GetSourceExpression(source2) )); + } [DynamicDependency("Intersect`1", typeof(Enumerable))] - public static IQueryable Intersect(this IQueryable source1!!, IEnumerable source2!!, IEqualityComparer? comparer) => - source1.Provider.CreateQuery( + public static IQueryable Intersect(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Intersect_TSource_3(typeof(TSource)), @@ -537,6 +832,7 @@ public static IQueryable Intersect(this IQueryable so GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } /// Produces the set intersection of two sequences according to a specified key selector function. /// The type of the elements of the input sequences. @@ -547,8 +843,13 @@ public static IQueryable Intersect(this IQueryable so /// A sequence that contains the elements that form the set intersection of two sequences. /// or is . [DynamicDependency("IntersectBy`2", typeof(Enumerable))] - public static IQueryable IntersectBy(this IQueryable source1!!, IEnumerable source2!!, Expression> keySelector!!) => - source1.Provider.CreateQuery( + public static IQueryable IntersectBy(this IQueryable source1, IEnumerable source2, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(keySelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.IntersectBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), @@ -556,6 +857,7 @@ public static IQueryable IntersectBy(this IQueryableProduces the set intersection of two sequences according to a specified key selector function. /// The type of the elements of the input sequences. @@ -567,8 +869,13 @@ public static IQueryable IntersectBy(this IQueryableA sequence that contains the elements that form the set intersection of two sequences. /// or is . [DynamicDependency("IntersectBy`2", typeof(Enumerable))] - public static IQueryable IntersectBy(this IQueryable source1!!, IEnumerable source2!!, Expression> keySelector!!, IEqualityComparer? comparer) => - source1.Provider.CreateQuery( + public static IQueryable IntersectBy(this IQueryable source1, IEnumerable source2, Expression> keySelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(keySelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.IntersectBy_TSource_TKey_4(typeof(TSource), typeof(TKey)), @@ -577,19 +884,29 @@ public static IQueryable IntersectBy(this IQueryable)) )); + } [DynamicDependency("Except`1", typeof(Enumerable))] - public static IQueryable Except(this IQueryable source1!!, IEnumerable source2!!) => - source1.Provider.CreateQuery( + public static IQueryable Except(this IQueryable source1, IEnumerable source2) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Except_TSource_2(typeof(TSource)), source1.Expression, GetSourceExpression(source2) )); + } [DynamicDependency("Except`1", typeof(Enumerable))] - public static IQueryable Except(this IQueryable source1!!, IEnumerable source2!!, IEqualityComparer? comparer) => - source1.Provider.CreateQuery( + public static IQueryable Except(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Except_TSource_3(typeof(TSource)), @@ -597,6 +914,7 @@ public static IQueryable Except(this IQueryable sourc GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } /// /// Produces the set difference of two sequences according to a specified key selector function. @@ -608,8 +926,13 @@ public static IQueryable Except(this IQueryable sourc /// A function to extract the key for each element. /// A that contains the set difference of the elements of two sequences. [DynamicDependency("ExceptBy`2", typeof(Enumerable))] - public static IQueryable ExceptBy(this IQueryable source1!!, IEnumerable source2!!, Expression> keySelector!!) => - source1.Provider.CreateQuery( + public static IQueryable ExceptBy(this IQueryable source1, IEnumerable source2, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(keySelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.ExceptBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), @@ -617,6 +940,7 @@ public static IQueryable ExceptBy(this IQueryable /// Produces the set difference of two sequences according to a specified key selector function. @@ -629,8 +953,13 @@ public static IQueryable ExceptBy(this IQueryableAn to compare keys. /// A that contains the set difference of the elements of two sequences. [DynamicDependency("ExceptBy`2", typeof(Enumerable))] - public static IQueryable ExceptBy(this IQueryable source1!!, IEnumerable source2!!, Expression> keySelector!!, IEqualityComparer? comparer) => - source1.Provider.CreateQuery( + public static IQueryable ExceptBy(this IQueryable source1, IEnumerable source2, Expression> keySelector, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + ArgumentNullException.ThrowIfNull(keySelector); + + return source1.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.ExceptBy_TSource_TKey_4(typeof(TSource), typeof(TKey)), @@ -639,29 +968,43 @@ public static IQueryable ExceptBy(this IQueryable)) )); + } [DynamicDependency("First`1", typeof(Enumerable))] - public static TSource First(this IQueryable source!!) => - source.Provider.Execute( + public static TSource First(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.First_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("First`1", typeof(Enumerable))] - public static TSource First(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static TSource First(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.First_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("FirstOrDefault`1", typeof(Enumerable))] - public static TSource? FirstOrDefault(this IQueryable source!!) => - source.Provider.Execute( + public static TSource? FirstOrDefault(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.FirstOrDefault_TSource_1(typeof(TSource)), source.Expression)); + } /// Returns the first element of a sequence, or a default value if the sequence contains no elements. /// The type of the elements of . @@ -670,21 +1013,30 @@ public static TSource First(this IQueryable source!!, Expressi /// if is empty; otherwise, the first element in . /// is . [DynamicDependency("FirstOrDefault`1", typeof(Enumerable))] - public static TSource FirstOrDefault(this IQueryable source!!, TSource defaultValue) => - source.Provider.Execute( + public static TSource FirstOrDefault(this IQueryable source, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.FirstOrDefault_TSource_3(typeof(TSource)), source.Expression, Expression.Constant(defaultValue, typeof(TSource)))); + } [DynamicDependency("FirstOrDefault`1", typeof(Enumerable))] - public static TSource? FirstOrDefault(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static TSource? FirstOrDefault(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.FirstOrDefault_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } /// Returns the first element of the sequence that satisfies a condition or a default value if no such element is found. /// The type of the elements of . @@ -694,36 +1046,54 @@ public static TSource FirstOrDefault(this IQueryable source!!, /// if is empty or if no element passes the test specified by ; otherwise, the first element in that passes the test specified by . /// or is . [DynamicDependency("FirstOrDefault`1", typeof(Enumerable))] - public static TSource FirstOrDefault(this IQueryable source!!, Expression> predicate!!, TSource defaultValue) => - source.Provider.Execute( + public static TSource FirstOrDefault(this IQueryable source, Expression> predicate, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.FirstOrDefault_TSource_4(typeof(TSource)), source.Expression, Expression.Quote(predicate), Expression.Constant(defaultValue, typeof(TSource)) )); + } [DynamicDependency("Last`1", typeof(Enumerable))] - public static TSource Last(this IQueryable source!!) => - source.Provider.Execute( + public static TSource Last(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Last_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("Last`1", typeof(Enumerable))] - public static TSource Last(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static TSource Last(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Last_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("LastOrDefault`1", typeof(Enumerable))] - public static TSource? LastOrDefault(this IQueryable source!!) => - source.Provider.Execute( + public static TSource? LastOrDefault(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.LastOrDefault_TSource_1(typeof(TSource)), source.Expression)); + } /// Returns the last element of a sequence, or a default value if the sequence contains no elements. /// The type of the elements of . @@ -732,21 +1102,30 @@ public static TSource Last(this IQueryable source!!, Expressio /// if the source sequence is empty; otherwise, the last element in the . /// is . [DynamicDependency("LastOrDefault`1", typeof(Enumerable))] - public static TSource LastOrDefault(this IQueryable source!!, TSource defaultValue) => - source.Provider.Execute( + public static TSource LastOrDefault(this IQueryable source, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.LastOrDefault_TSource_3(typeof(TSource)), source.Expression, Expression.Constant(defaultValue, typeof(TSource)))); + } [DynamicDependency("LastOrDefault`1", typeof(Enumerable))] - public static TSource? LastOrDefault(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static TSource? LastOrDefault(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.LastOrDefault_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } /// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found. /// The type of the elements of . @@ -756,36 +1135,54 @@ public static TSource LastOrDefault(this IQueryable source!!, /// if the sequence is empty or if no elements pass the test in the predicate function; otherwise, the last element that passes the test in the predicate function. /// or is . [DynamicDependency("LastOrDefault`1", typeof(Enumerable))] - public static TSource LastOrDefault(this IQueryable source!!, Expression> predicate!!, TSource defaultValue) => - source.Provider.Execute( + public static TSource LastOrDefault(this IQueryable source, Expression> predicate, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.LastOrDefault_TSource_4(typeof(TSource)), source.Expression, Expression.Quote(predicate), Expression.Constant(defaultValue, typeof(TSource)) )); + } [DynamicDependency("Single`1", typeof(Enumerable))] - public static TSource Single(this IQueryable source!!) => - source.Provider.Execute( + public static TSource Single(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Single_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("Single`1", typeof(Enumerable))] - public static TSource Single(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static TSource Single(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Single_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("SingleOrDefault`1", typeof(Enumerable))] - public static TSource? SingleOrDefault(this IQueryable source!!) => - source.Provider.Execute( + public static TSource? SingleOrDefault(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.SingleOrDefault_TSource_1(typeof(TSource)), source.Expression)); + } /// Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence. /// The type of the elements of . @@ -795,21 +1192,30 @@ public static TSource Single(this IQueryable source!!, Express /// is . /// The input sequence contains more than one element. [DynamicDependency("SingleOrDefault`1", typeof(Enumerable))] - public static TSource SingleOrDefault(this IQueryable source!!, TSource defaultValue) => - source.Provider.Execute( + public static TSource SingleOrDefault(this IQueryable source, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.SingleOrDefault_TSource_3(typeof(TSource)), source.Expression, Expression.Constant(defaultValue, typeof(TSource)))); + } [DynamicDependency("SingleOrDefault`1", typeof(Enumerable))] - public static TSource? SingleOrDefault(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static TSource? SingleOrDefault(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.SingleOrDefault_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } /// Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition. /// The type of the elements of . @@ -820,19 +1226,27 @@ public static TSource SingleOrDefault(this IQueryable source!! /// or is . /// More than one element satisfies the condition in . [DynamicDependency("SingleOrDefault`1", typeof(Enumerable))] - public static TSource SingleOrDefault(this IQueryable source!!, Expression> predicate!!, TSource defaultValue) => - source.Provider.Execute( + public static TSource SingleOrDefault(this IQueryable source, Expression> predicate, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.SingleOrDefault_TSource_4(typeof(TSource)), source.Expression, Expression.Quote(predicate), Expression.Constant(defaultValue, typeof(TSource)) )); + } [DynamicDependency("ElementAt`1", typeof(Enumerable))] - public static TSource ElementAt(this IQueryable source!!, int index) + public static TSource ElementAt(this IQueryable source, int index) { + ArgumentNullException.ThrowIfNull(source); + if (index < 0) throw Error.ArgumentOutOfRange(nameof(index)); + return source.Provider.Execute( Expression.Call( null, @@ -849,10 +1263,13 @@ public static TSource ElementAt(this IQueryable source!!, int /// is outside the bounds of the sequence. /// The element at the specified position in the sequence. [DynamicDependency("ElementAt`1", typeof(Enumerable))] - public static TSource ElementAt(this IQueryable source!!, Index index) + public static TSource ElementAt(this IQueryable source, Index index) { + ArgumentNullException.ThrowIfNull(source); + if (index.IsFromEnd && index.Value == 0) throw Error.ArgumentOutOfRange(nameof(index)); + return source.Provider.Execute( Expression.Call( null, @@ -862,13 +1279,17 @@ public static TSource ElementAt(this IQueryable source!!, Inde } [DynamicDependency("ElementAtOrDefault`1", typeof(Enumerable))] - public static TSource? ElementAtOrDefault(this IQueryable source!!, int index) => - source.Provider.Execute( + public static TSource? ElementAtOrDefault(this IQueryable source, int index) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.ElementAtOrDefault_Int32_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(index) )); + } /// Returns the element at a specified index in a sequence or a default value if the index is out of range. /// The type of the elements of . @@ -877,67 +1298,100 @@ public static TSource ElementAt(this IQueryable source!!, Inde /// is . /// if is outside the bounds of the sequence; otherwise, the element at the specified position in the sequence. [DynamicDependency("ElementAtOrDefault`1", typeof(Enumerable))] - public static TSource? ElementAtOrDefault(this IQueryable source!!, Index index) => - source.Provider.Execute( + public static TSource? ElementAtOrDefault(this IQueryable source, Index index) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.ElementAtOrDefault_Index_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(index) )); + } [DynamicDependency("DefaultIfEmpty`1", typeof(Enumerable))] - public static IQueryable DefaultIfEmpty(this IQueryable source!!) => - source.Provider.CreateQuery( + public static IQueryable DefaultIfEmpty(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.DefaultIfEmpty_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("DefaultIfEmpty`1", typeof(Enumerable))] - public static IQueryable DefaultIfEmpty(this IQueryable source!!, TSource defaultValue) => - source.Provider.CreateQuery( + public static IQueryable DefaultIfEmpty(this IQueryable source, TSource defaultValue) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.DefaultIfEmpty_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(defaultValue, typeof(TSource)) )); + } [DynamicDependency("Contains`1", typeof(Enumerable))] - public static bool Contains(this IQueryable source!!, TSource item) => - source.Provider.Execute( + public static bool Contains(this IQueryable source, TSource item) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Contains_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(item, typeof(TSource)) )); + } [DynamicDependency("Contains`1", typeof(Enumerable))] - public static bool Contains(this IQueryable source!!, TSource item, IEqualityComparer? comparer) => - source.Provider.Execute( + public static bool Contains(this IQueryable source, TSource item, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Contains_TSource_3(typeof(TSource)), source.Expression, Expression.Constant(item, typeof(TSource)), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } [DynamicDependency("Reverse`1", typeof(Enumerable))] - public static IQueryable Reverse(this IQueryable source!!) => - source.Provider.CreateQuery( + public static IQueryable Reverse(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Reverse_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("SequenceEqual`1", typeof(Enumerable))] - public static bool SequenceEqual(this IQueryable source1!!, IEnumerable source2!!) => - source1.Provider.Execute( + public static bool SequenceEqual(this IQueryable source1, IEnumerable source2) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.Execute( Expression.Call( null, CachedReflectionInfo.SequenceEqual_TSource_2(typeof(TSource)), source1.Expression, GetSourceExpression(source2) )); + } [DynamicDependency("SequenceEqual`1", typeof(Enumerable))] - public static bool SequenceEqual(this IQueryable source1!!, IEnumerable source2!!, IEqualityComparer? comparer) => - source1.Provider.Execute( + public static bool SequenceEqual(this IQueryable source1, IEnumerable source2, IEqualityComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source1); + ArgumentNullException.ThrowIfNull(source2); + + return source1.Provider.Execute( Expression.Call( null, CachedReflectionInfo.SequenceEqual_TSource_3(typeof(TSource)), @@ -945,70 +1399,107 @@ public static bool SequenceEqual(this IQueryable source1!!, IE GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer)) )); + } [DynamicDependency("Any`1", typeof(Enumerable))] - public static bool Any(this IQueryable source!!) => - source.Provider.Execute( + public static bool Any(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Any_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("Any`1", typeof(Enumerable))] - public static bool Any(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static bool Any(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Any_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("All`1", typeof(Enumerable))] - public static bool All(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static bool All(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.All_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("Count`1", typeof(Enumerable))] - public static int Count(this IQueryable source!!) => - source.Provider.Execute( + public static int Count(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Count_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("Count`1", typeof(Enumerable))] - public static int Count(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static int Count(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Count_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("LongCount`1", typeof(Enumerable))] - public static long LongCount(this IQueryable source!!) => - source.Provider.Execute( + public static long LongCount(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.LongCount_TSource_1(typeof(TSource)), source.Expression)); + } [DynamicDependency("LongCount`1", typeof(Enumerable))] - public static long LongCount(this IQueryable source!!, Expression> predicate!!) => - source.Provider.Execute( + public static long LongCount(this IQueryable source, Expression> predicate) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(predicate); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.LongCount_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(predicate) )); + } [DynamicDependency("Min`1", typeof(Enumerable))] - public static TSource? Min(this IQueryable source!!) => - source.Provider.Execute( + public static TSource? Min(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Min_TSource_1(typeof(TSource)), source.Expression)); + } /// Returns the minimum value in a generic . /// The type of the elements of . @@ -1018,23 +1509,32 @@ public static long LongCount(this IQueryable source!!, Express /// is . /// No object in implements the or interface. [DynamicDependency("Min`1", typeof(Enumerable))] - public static TSource? Min(this IQueryable source!!, IComparer? comparer) => - source.Provider.Execute( + public static TSource? Min(this IQueryable source, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Min_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("Min`2", typeof(Enumerable))] - public static TResult? Min(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static TResult? Min(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Min_TSource_TResult_2(typeof(TSource), typeof(TResult)), source.Expression, Expression.Quote(selector) )); + } /// Returns the minimum value in a generic according to a specified key selector function. /// The type of the elements of . @@ -1045,14 +1545,19 @@ public static long LongCount(this IQueryable source!!, Express /// is . /// No key extracted from implements the or interface. [DynamicDependency("MinBy`2", typeof(Enumerable))] - public static TSource? MinBy(this IQueryable source!!, Expression> keySelector!!) => - source.Provider.Execute( + public static TSource? MinBy(this IQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.MinBy_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } /// Returns the minimum value in a generic according to a specified key selector function. /// The type of the elements of . @@ -1064,8 +1569,12 @@ public static long LongCount(this IQueryable source!!, Express /// is . /// No key extracted from implements the or interface. [DynamicDependency("MinBy`2", typeof(Enumerable))] - public static TSource? MinBy(this IQueryable source!!, Expression> keySelector!!, IComparer? comparer) => - source.Provider.Execute( + public static TSource? MinBy(this IQueryable source, Expression> keySelector, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.MinBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), @@ -1073,13 +1582,19 @@ public static long LongCount(this IQueryable source!!, Express Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("Max`1", typeof(Enumerable))] - public static TSource? Max(this IQueryable source!!) => - source.Provider.Execute( + public static TSource? Max(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Max_TSource_1(typeof(TSource)), source.Expression)); + } + /// Returns the maximum value in a generic . /// The type of the elements of . /// A sequence of values to determine the maximum value of. @@ -1087,23 +1602,32 @@ public static long LongCount(this IQueryable source!!, Express /// The maximum value in the sequence. /// is . [DynamicDependency("Max`1", typeof(Enumerable))] - public static TSource? Max(this IQueryable source!!, IComparer? comparer) => - source.Provider.Execute( + public static TSource? Max(this IQueryable source, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Max_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("Max`2", typeof(Enumerable))] - public static TResult? Max(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static TResult? Max(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Max_TSource_TResult_2(typeof(TSource), typeof(TResult)), source.Expression, Expression.Quote(selector) )); + } /// Returns the maximum value in a generic according to a specified key selector function. /// The type of the elements of . @@ -1114,14 +1638,19 @@ public static long LongCount(this IQueryable source!!, Express /// is . /// No key extracted from implements the or interface. [DynamicDependency("MaxBy`2", typeof(Enumerable))] - public static TSource? MaxBy(this IQueryable source!!, Expression> keySelector!!) => - source.Provider.Execute( + public static TSource? MaxBy(this IQueryable source, Expression> keySelector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.MaxBy_TSource_TKey_2(typeof(TSource), typeof(TKey)), source.Expression, Expression.Quote(keySelector) )); + } /// Returns the maximum value in a generic according to a specified key selector function. /// The type of the elements of . @@ -1133,8 +1662,12 @@ public static long LongCount(this IQueryable source!!, Express /// is . /// No key extracted from implements the or interface. [DynamicDependency("MaxBy`2", typeof(Enumerable))] - public static TSource? MaxBy(this IQueryable source!!, Expression> keySelector!!, IComparer? comparer) => - source.Provider.Execute( + public static TSource? MaxBy(this IQueryable source, Expression> keySelector, IComparer? comparer) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(keySelector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.MaxBy_TSource_TKey_3(typeof(TSource), typeof(TKey)), @@ -1142,386 +1675,599 @@ public static long LongCount(this IQueryable source!!, Express Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer)) )); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static int Sum(this IQueryable source!!) => - source.Provider.Execute( + public static int Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Int32_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static int? Sum(this IQueryable source!!) => - source.Provider.Execute( + public static int? Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableInt32_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static long Sum(this IQueryable source!!) => - source.Provider.Execute( + public static long Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Int64_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static long? Sum(this IQueryable source!!) => - source.Provider.Execute( + public static long? Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableInt64_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static float Sum(this IQueryable source!!) => - source.Provider.Execute( + public static float Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Single_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static float? Sum(this IQueryable source!!) => - source.Provider.Execute( + public static float? Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableSingle_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static double Sum(this IQueryable source!!) => - source.Provider.Execute( + public static double Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Double_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static double? Sum(this IQueryable source!!) => - source.Provider.Execute( + public static double? Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableDouble_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static decimal Sum(this IQueryable source!!) => - source.Provider.Execute( + public static decimal Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Decimal_1, source.Expression)); + } [DynamicDependency("Sum", typeof(Enumerable))] - public static decimal? Sum(this IQueryable source!!) => - source.Provider.Execute( + public static decimal? Sum(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableDecimal_1, source.Expression)); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static int Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static int Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Int32_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static int? Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static int? Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableInt32_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static long Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static long Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Int64_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static long? Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static long? Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableInt64_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static float Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static float Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Single_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static float? Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static float? Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableSingle_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static double Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Double_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static double? Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double? Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableDouble_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static decimal Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static decimal Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_Decimal_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Sum`1", typeof(Enumerable))] - public static decimal? Sum(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static decimal? Sum(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Sum_NullableDecimal_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average", typeof(Enumerable))] - public static double Average(this IQueryable source!!) => - source.Provider.Execute( + public static double Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Int32_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static double? Average(this IQueryable source!!) => - source.Provider.Execute( + public static double? Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableInt32_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static double Average(this IQueryable source!!) => - source.Provider.Execute( + public static double Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Int64_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static double? Average(this IQueryable source!!) => - source.Provider.Execute( + public static double? Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableInt64_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static float Average(this IQueryable source!!) => - source.Provider.Execute( + public static float Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Single_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static float? Average(this IQueryable source!!) => - source.Provider.Execute( + public static float? Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableSingle_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static double Average(this IQueryable source!!) => - source.Provider.Execute( + public static double Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Double_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static double? Average(this IQueryable source!!) => - source.Provider.Execute( + public static double? Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableDouble_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static decimal Average(this IQueryable source!!) => - source.Provider.Execute( + public static decimal Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Decimal_1, source.Expression)); + } [DynamicDependency("Average", typeof(Enumerable))] - public static decimal? Average(this IQueryable source!!) => - source.Provider.Execute( + public static decimal? Average(this IQueryable source) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableDecimal_1, source.Expression)); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static double Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Int32_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static double? Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double? Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableInt32_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static float Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static float Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Single_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static float? Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static float? Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableSingle_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static double Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Int64_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static double? Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double? Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableInt64_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static double Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Double_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static double? Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static double? Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableDouble_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static decimal Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static decimal Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_Decimal_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Average`1", typeof(Enumerable))] - public static decimal? Average(this IQueryable source!!, Expression> selector!!) => - source.Provider.Execute( + public static decimal? Average(this IQueryable source, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Average_NullableDecimal_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(selector) )); + } [DynamicDependency("Aggregate`1", typeof(Enumerable))] - public static TSource Aggregate(this IQueryable source!!, Expression> func!!) => - source.Provider.Execute( + public static TSource Aggregate(this IQueryable source, Expression> func) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Aggregate_TSource_2(typeof(TSource)), source.Expression, Expression.Quote(func) )); + } [DynamicDependency("Aggregate`2", typeof(Enumerable))] - public static TAccumulate Aggregate(this IQueryable source!!, TAccumulate seed, Expression> func!!) => - source.Provider.Execute( + public static TAccumulate Aggregate(this IQueryable source, TAccumulate seed, Expression> func) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Aggregate_TSource_TAccumulate_3(typeof(TSource), typeof(TAccumulate)), source.Expression, Expression.Constant(seed), Expression.Quote(func) )); + } [DynamicDependency("Aggregate`3", typeof(Enumerable))] - public static TResult Aggregate(this IQueryable source!!, TAccumulate seed, Expression> func!!, Expression> selector!!) => - source.Provider.Execute( + public static TResult Aggregate(this IQueryable source, TAccumulate seed, Expression> func, Expression> selector) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(func); + ArgumentNullException.ThrowIfNull(selector); + + return source.Provider.Execute( Expression.Call( null, CachedReflectionInfo.Aggregate_TSource_TAccumulate_TResult_4(typeof(TSource), typeof(TAccumulate), typeof(TResult)), source.Expression, Expression.Constant(seed), Expression.Quote(func), Expression.Quote(selector))); + } [DynamicDependency("SkipLast`1", typeof(Enumerable))] - public static IQueryable SkipLast(this IQueryable source!!, int count) => - source.Provider.CreateQuery( + public static IQueryable SkipLast(this IQueryable source, int count) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.SkipLast_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(count) )); + } [DynamicDependency("TakeLast`1", typeof(Enumerable))] - public static IQueryable TakeLast(this IQueryable source!!, int count) => - source.Provider.CreateQuery( + public static IQueryable TakeLast(this IQueryable source, int count) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.TakeLast_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(count) )); + } [DynamicDependency("Append`1", typeof(Enumerable))] - public static IQueryable Append(this IQueryable source!!, TSource element) => - source.Provider.CreateQuery( + public static IQueryable Append(this IQueryable source, TSource element) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Append_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(element) )); + } [DynamicDependency("Prepend`1", typeof(Enumerable))] - public static IQueryable Prepend(this IQueryable source!!, TSource element) => - source.Provider.CreateQuery( + public static IQueryable Prepend(this IQueryable source, TSource element) + { + ArgumentNullException.ThrowIfNull(source); + + return source.Provider.CreateQuery( Expression.Call( null, CachedReflectionInfo.Prepend_TSource_2(typeof(TSource)), source.Expression, Expression.Constant(element) )); + } } } diff --git a/src/libraries/System.Memory.Data/src/System/BinaryData.cs b/src/libraries/System.Memory.Data/src/System/BinaryData.cs index 889c303df445bf..b9ab1994c8d84b 100644 --- a/src/libraries/System.Memory.Data/src/System/BinaryData.cs +++ b/src/libraries/System.Memory.Data/src/System/BinaryData.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; @@ -33,9 +33,9 @@ public class BinaryData /// provided byte array. /// /// The array to wrap. - public BinaryData(byte[] data!!) + public BinaryData(byte[] data) { - _bytes = data; + _bytes = data ?? throw new ArgumentNullException(nameof(data)); } /// @@ -70,8 +70,13 @@ public BinaryData(ReadOnlyMemory data) /// the string to bytes using the UTF-8 encoding. /// /// The string data. - public BinaryData(string data!!) + public BinaryData(string data) { + if (data is null) + { + throw new ArgumentNullException(nameof(data)); + } + _bytes = Encoding.UTF8.GetBytes(data); } @@ -105,8 +110,13 @@ public BinaryData(string data!!) /// /// Stream containing the data. /// A value representing all of the data remaining in . - public static BinaryData FromStream(Stream stream!!) + public static BinaryData FromStream(Stream stream) { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + return FromStreamAsync(stream, async: false).GetAwaiter().GetResult(); } @@ -117,8 +127,13 @@ public static BinaryData FromStream(Stream stream!!) /// Stream containing the data. /// A token that may be used to cancel the operation. /// A value representing all of the data remaining in . - public static Task FromStreamAsync(Stream stream!!, CancellationToken cancellationToken = default) + public static Task FromStreamAsync(Stream stream, CancellationToken cancellationToken = default) { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + return FromStreamAsync(stream, async: true, cancellationToken); } diff --git a/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs b/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs index 72bbd7af7da6ac..2441e016c2d7a9 100644 --- a/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs +++ b/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs @@ -31,8 +31,11 @@ public static class EncodingExtensions /// The buffer to which the encoded bytes will be written. /// Thrown if contains data that cannot be encoded and is configured /// to throw an exception when such data is seen. - public static long GetBytes(this Encoding encoding!!, ReadOnlySpan chars, IBufferWriter writer!!) + public static long GetBytes(this Encoding encoding, ReadOnlySpan chars, IBufferWriter writer) { + ArgumentNullException.ThrowIfNull(encoding); + ArgumentNullException.ThrowIfNull(writer); + if (chars.Length <= MaxInputElementsPerIteration) { // The input span is small enough where we can one-shot this. @@ -64,8 +67,10 @@ public static long GetBytes(this Encoding encoding!!, ReadOnlySpan chars, /// The number of bytes written to . /// Thrown if contains data that cannot be encoded and is configured /// to throw an exception when such data is seen. - public static long GetBytes(this Encoding encoding!!, in ReadOnlySequence chars, IBufferWriter writer!!) + public static long GetBytes(this Encoding encoding, in ReadOnlySequence chars, IBufferWriter writer) { + ArgumentNullException.ThrowIfNull(encoding); + ArgumentNullException.ThrowIfNull(writer); // Delegate to the Span-based method if possible. // If that doesn't work, allocate the Encoder instance and run a loop. @@ -92,8 +97,10 @@ public static long GetBytes(this Encoding encoding!!, in ReadOnlySequence /// Thrown if is not large enough to contain the encoded form of . /// Thrown if contains data that cannot be encoded and is configured /// to throw an exception when such data is seen. - public static int GetBytes(this Encoding encoding!!, in ReadOnlySequence chars, Span bytes) + public static int GetBytes(this Encoding encoding, in ReadOnlySequence chars, Span bytes) { + ArgumentNullException.ThrowIfNull(encoding); + if (chars.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -132,8 +139,10 @@ public static int GetBytes(this Encoding encoding!!, in ReadOnlySequence c /// A array which represents the encoded contents of . /// Thrown if contains data that cannot be encoded and is configured /// to throw an exception when such data is seen. - public static byte[] GetBytes(this Encoding encoding!!, in ReadOnlySequence chars) + public static byte[] GetBytes(this Encoding encoding, in ReadOnlySequence chars) { + ArgumentNullException.ThrowIfNull(encoding); + if (chars.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -213,8 +222,11 @@ public static byte[] GetBytes(this Encoding encoding!!, in ReadOnlySequenceThe number of chars written to . /// Thrown if contains data that cannot be decoded and is configured /// to throw an exception when such data is seen. - public static long GetChars(this Encoding encoding!!, ReadOnlySpan bytes, IBufferWriter writer!!) + public static long GetChars(this Encoding encoding, ReadOnlySpan bytes, IBufferWriter writer) { + ArgumentNullException.ThrowIfNull(encoding); + ArgumentNullException.ThrowIfNull(writer); + if (bytes.Length <= MaxInputElementsPerIteration) { // The input span is small enough where we can one-shot this. @@ -246,8 +258,11 @@ public static long GetChars(this Encoding encoding!!, ReadOnlySpan bytes, /// The number of chars written to . /// Thrown if contains data that cannot be decoded and is configured /// to throw an exception when such data is seen. - public static long GetChars(this Encoding encoding!!, in ReadOnlySequence bytes, IBufferWriter writer!!) + public static long GetChars(this Encoding encoding, in ReadOnlySequence bytes, IBufferWriter writer) { + ArgumentNullException.ThrowIfNull(encoding); + ArgumentNullException.ThrowIfNull(writer); + // Delegate to the Span-based method if possible. // If that doesn't work, allocate the Encoder instance and run a loop. @@ -273,8 +288,10 @@ public static long GetChars(this Encoding encoding!!, in ReadOnlySequence /// Thrown if is not large enough to contain the encoded form of . /// Thrown if contains data that cannot be decoded and is configured /// to throw an exception when such data is seen. - public static int GetChars(this Encoding encoding!!, in ReadOnlySequence bytes, Span chars) + public static int GetChars(this Encoding encoding, in ReadOnlySequence bytes, Span chars) { + ArgumentNullException.ThrowIfNull(encoding); + if (bytes.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -313,8 +330,10 @@ public static int GetChars(this Encoding encoding!!, in ReadOnlySequence b /// A which represents the decoded contents of . /// Thrown if contains data that cannot be decoded and is configured /// to throw an exception when such data is seen. - public static string GetString(this Encoding encoding!!, in ReadOnlySequence bytes) + public static string GetString(this Encoding encoding, in ReadOnlySequence bytes) { + ArgumentNullException.ThrowIfNull(encoding); + if (bytes.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -392,8 +411,11 @@ public static string GetString(this Encoding encoding!!, in ReadOnlySequence /// Thrown if contains data that cannot be encoded and is configured /// to throw an exception when such data is seen. - public static void Convert(this Encoder encoder!!, ReadOnlySpan chars, IBufferWriter writer!!, bool flush, out long bytesUsed, out bool completed) + public static void Convert(this Encoder encoder, ReadOnlySpan chars, IBufferWriter writer, bool flush, out long bytesUsed, out bool completed) { + ArgumentNullException.ThrowIfNull(encoder); + ArgumentNullException.ThrowIfNull(writer); + // We need to perform at least one iteration of the loop since the encoder could have internal state. long totalBytesWritten = 0; @@ -475,8 +497,11 @@ public static void Convert(this Encoder encoder, in ReadOnlySequence chars /// /// Thrown if contains data that cannot be encoded and is configured /// to throw an exception when such data is seen. - public static void Convert(this Decoder decoder!!, ReadOnlySpan bytes, IBufferWriter writer!!, bool flush, out long charsUsed, out bool completed) + public static void Convert(this Decoder decoder, ReadOnlySpan bytes, IBufferWriter writer, bool flush, out long charsUsed, out bool completed) { + ArgumentNullException.ThrowIfNull(decoder); + ArgumentNullException.ThrowIfNull(writer); + // We need to perform at least one iteration of the loop since the decoder could have internal state. long totalCharsWritten = 0; diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs index 0d926349173b22..de622bef73625b 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Get.cs @@ -16,53 +16,93 @@ namespace System.Net.Http.Json public static partial class HttpClientJsonExtensions { [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task GetFromJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, type, options, cancellationToken); } [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task GetFromJsonAsync(this HttpClient client!!, Uri? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, Uri? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, type, options, cancellationToken); } [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task GetFromJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, options, cancellationToken); } [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task GetFromJsonAsync(this HttpClient client!!, Uri? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, Uri? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, options, cancellationToken); } - public static Task GetFromJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, type, context, cancellationToken); } - public static Task GetFromJsonAsync(this HttpClient client!!, Uri? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, Uri? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, type, context, cancellationToken); } - public static Task GetFromJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, jsonTypeInfo, cancellationToken); } - public static Task GetFromJsonAsync(this HttpClient client!!, Uri? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client, Uri? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + Task taskResponse = client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); return GetFromJsonAsyncCore(taskResponse, jsonTypeInfo, cancellationToken); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs index c1d2c20615420c..6e337de20aa58a 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Patch.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; @@ -23,8 +23,13 @@ public static partial class HttpClientJsonExtensions /// The task object representing the asynchronous operation. /// The is null. [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PatchAsJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PatchAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PatchAsync(requestUri, content, cancellationToken); } @@ -41,8 +46,13 @@ public static Task PatchAsJsonAsync(this HttpClient /// The task object representing the asynchronous operation. /// The is null. [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PatchAsJsonAsync(this HttpClient client!!, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PatchAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PatchAsync(requestUri, content, cancellationToken); } @@ -86,8 +96,13 @@ public static Task PatchAsJsonAsync(this HttpClient /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// The task object representing the asynchronous operation. /// The is null. - public static Task PatchAsJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PatchAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = new(value, jsonTypeInfo); return client.PatchAsync(requestUri, content, cancellationToken); } @@ -103,8 +118,13 @@ public static Task PatchAsJsonAsync(this HttpClient /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// The task object representing the asynchronous operation. /// The is null. - public static Task PatchAsJsonAsync(this HttpClient client!!, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PatchAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = new(value, jsonTypeInfo); return client.PatchAsync(requestUri, content, cancellationToken); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs index 47e92180b2c37d..6d830a00e3b513 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Post.cs @@ -12,15 +12,25 @@ namespace System.Net.Http.Json public static partial class HttpClientJsonExtensions { [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PostAsJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PostAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PostAsync(requestUri, content, cancellationToken); } [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PostAsJsonAsync(this HttpClient client!!, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PostAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PostAsync(requestUri, content, cancellationToken); } @@ -33,14 +43,24 @@ public static Task PostAsJsonAsync(this HttpClient public static Task PostAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, CancellationToken cancellationToken) => client.PostAsJsonAsync(requestUri, value, options: null, cancellationToken); - public static Task PostAsJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PostAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = new(value, jsonTypeInfo); return client.PostAsync(requestUri, content, cancellationToken); } - public static Task PostAsJsonAsync(this HttpClient client!!, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PostAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = new(value, jsonTypeInfo); return client.PostAsync(requestUri, content, cancellationToken); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs index 9ffdbf9171b045..e4b485aa8916b0 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Put.cs @@ -12,15 +12,25 @@ namespace System.Net.Http.Json public static partial class HttpClientJsonExtensions { [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PutAsJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PutAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PutAsync(requestUri, content, cancellationToken); } [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PutAsJsonAsync(this HttpClient client!!, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PutAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PutAsync(requestUri, content, cancellationToken); } @@ -33,14 +43,24 @@ public static Task PutAsJsonAsync(this HttpClient c public static Task PutAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, CancellationToken cancellationToken) => client.PutAsJsonAsync(requestUri, value, options: null, cancellationToken); - public static Task PutAsJsonAsync(this HttpClient client!!, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PutAsJsonAsync(this HttpClient client, [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = new(value, jsonTypeInfo); return client.PutAsync(requestUri, content, cancellationToken); } - public static Task PutAsJsonAsync(this HttpClient client!!, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PutAsJsonAsync(this HttpClient client, Uri? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + JsonContent content = new(value, jsonTypeInfo); return client.PutAsync(requestUri, content, cancellationToken); } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs index 8f2d951f9c39ae..6a9a5f8b830d99 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.cs @@ -17,16 +17,26 @@ public static partial class HttpContentJsonExtensions internal const string SerializationUnreferencedCodeMessage = "JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved."; [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static Task ReadFromJsonAsync(this HttpContent content!!, Type type, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task ReadFromJsonAsync(this HttpContent content, Type type, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + Encoding? sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet); return ReadFromJsonAsyncCore(content, type, sourceEncoding, options, cancellationToken); } [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static Task ReadFromJsonAsync(this HttpContent content!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task ReadFromJsonAsync(this HttpContent content, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + Encoding? sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet); return ReadFromJsonAsyncCore(content, sourceEncoding, options, cancellationToken); @@ -64,15 +74,25 @@ public static partial class HttpContentJsonExtensions private static ValueTask DeserializeAsyncHelper(Stream contentStream, JsonSerializerOptions? options, CancellationToken cancellationToken) => JsonSerializer.DeserializeAsync(contentStream, options, cancellationToken); - public static Task ReadFromJsonAsync(this HttpContent content!!, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) + public static Task ReadFromJsonAsync(this HttpContent content, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + Encoding? sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet); return ReadFromJsonAsyncCore(content, type, sourceEncoding, context, cancellationToken); } - public static Task ReadFromJsonAsync(this HttpContent content!!, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task ReadFromJsonAsync(this HttpContent content, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + Encoding? sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet); return ReadFromJsonAsyncCore(content, sourceEncoding, jsonTypeInfo, cancellationToken); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs index f9a620e0db7334..e13f79295a4b83 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContent.cs @@ -23,10 +23,15 @@ public sealed partial class JsonContent : HttpContent [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] private JsonContent( object? inputValue, - Type inputType!!, + Type inputType, MediaTypeHeaderValue? mediaType, JsonSerializerOptions? options) { + if (inputType is null) + { + throw new ArgumentNullException(nameof(inputType)); + } + if (inputValue != null && !inputType.IsAssignableFrom(inputValue.GetType())) { throw new ArgumentException(SR.Format(SR.SerializeWrongType, inputType, inputValue.GetType())); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContentOfT.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContentOfT.cs index d5ac1fca28d2d8..4044629b2756f9 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContentOfT.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/JsonContentOfT.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if !NETCOREAPP @@ -19,8 +19,13 @@ internal sealed partial class JsonContent : HttpContent private readonly TValue _typedValue; - public JsonContent(TValue inputValue, JsonTypeInfo jsonTypeInfo!!) + public JsonContent(TValue inputValue, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + throw new ArgumentNullException(nameof(jsonTypeInfo)); + } + _typeInfo = jsonTypeInfo; _typedValue = inputValue; Headers.ContentType = JsonHelpers.GetDefaultMediaType(); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs index c46d1cce0f43c0..eb1e66cccfc764 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs @@ -67,8 +67,13 @@ public override long Position public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - public override Task ReadAsync(byte[] buffer!!, int offset, int count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { + if (buffer is null) + { + throw new ArgumentNullException(nameof(buffer)); + } + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs index 1cc8bab3e48b26..024f7b886b3a89 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingWriteStream.cs @@ -66,8 +66,13 @@ public override void SetLength(long value) public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - public override Task WriteAsync(byte[] buffer!!, int offset, int count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { + if (buffer is null) + { + throw new ArgumentNullException(nameof(buffer)); + } + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs index 507a1beabd954f..f85402999f0a6f 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs @@ -568,9 +568,14 @@ protected override void Dispose(bool disposing) } protected override Task SendAsync( - HttpRequestMessage request!!, + HttpRequestMessage request, CancellationToken cancellationToken) { + if (request is null) + { + throw new ArgumentNullException(nameof(request)); + } + Uri? requestUri = request.RequestUri; if (requestUri is null || !requestUri.IsAbsoluteUri) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs index 68794b69b666e1..6d2fa2bd1df224 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestStream.cs @@ -97,8 +97,13 @@ public override Task FlushAsync(CancellationToken cancellationToken) Task.CompletedTask; } - public override Task WriteAsync(byte[] buffer!!, int offset, int count, CancellationToken token) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { + if (buffer is null) + { + throw new ArgumentNullException(nameof(buffer)); + } + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs index 5670b305fa408f..fd0bfee3375878 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs @@ -172,8 +172,13 @@ private async Task CopyToAsyncCore(Stream destination, byte[] buffer, Cancellati // request is made with a different buffer or when the state is cleared. } - public override Task ReadAsync(byte[] buffer!!, int offset, int count, CancellationToken token) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken token) { + if (buffer is null) + { + throw new ArgumentNullException(nameof(buffer)); + } + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs index 6f15e52b510c40..dc38ad705aebf9 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs @@ -143,189 +143,195 @@ protected internal override HttpResponseMessage Send(HttpRequestMessage request, throw new PlatformNotSupportedException(); } - protected internal override async Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) + protected internal override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - CancellationTokenRegistration? abortRegistration = null; - try - { - using var requestObject = new JSObject(); + ArgumentNullException.ThrowIfNull(request); + return Impl(request, cancellationToken); - if (request.Options.TryGetValue(FetchOptions, out IDictionary? fetchOptions)) + async Task Impl(HttpRequestMessage request, CancellationToken cancellationToken) + { + CancellationTokenRegistration? abortRegistration = null; + try { - foreach (KeyValuePair item in fetchOptions) + using var requestObject = new JSObject(); + + if (request.Options.TryGetValue(FetchOptions, out IDictionary? fetchOptions)) { - requestObject.SetObjectProperty(item.Key, item.Value); + foreach (KeyValuePair item in fetchOptions) + { + requestObject.SetObjectProperty(item.Key, item.Value); + } } - } - - requestObject.SetObjectProperty("method", request.Method.Method); - // Only set if property was specifically modified and is not default value - if (_isAllowAutoRedirectTouched) - { - // Allowing or Disallowing redirects. - // Here we will set redirect to `manual` instead of error if AllowAutoRedirect is - // false so there is no exception thrown - // - // https://developer.mozilla.org/en-US/docs/Web/API/Response/type - // - // other issues from whatwg/fetch: - // - // https://github.com/whatwg/fetch/issues/763 - // https://github.com/whatwg/fetch/issues/601 - requestObject.SetObjectProperty("redirect", AllowAutoRedirect ? "follow" : "manual"); - } + requestObject.SetObjectProperty("method", request.Method.Method); - // We need to check for body content - if (request.Content != null) - { - if (request.Content is StringContent) + // Only set if property was specifically modified and is not default value + if (_isAllowAutoRedirectTouched) { - requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true)); + // Allowing or Disallowing redirects. + // Here we will set redirect to `manual` instead of error if AllowAutoRedirect is + // false so there is no exception thrown + // + // https://developer.mozilla.org/en-US/docs/Web/API/Response/type + // + // other issues from whatwg/fetch: + // + // https://github.com/whatwg/fetch/issues/763 + // https://github.com/whatwg/fetch/issues/601 + requestObject.SetObjectProperty("redirect", AllowAutoRedirect ? "follow" : "manual"); } - else + + // We need to check for body content + if (request.Content != null) { - using (Uint8Array uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true))) + if (request.Content is StringContent) { - requestObject.SetObjectProperty("body", uint8Buffer); + requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true)); } - } - } - - // Process headers - // Cors has its own restrictions on headers. - // https://developer.mozilla.org/en-US/docs/Web/API/Headers - using (JSObject jsHeaders = new JSObject("Headers")) - { - foreach (KeyValuePair> header in request.Headers) - { - foreach (string value in header.Value) + else { - jsHeaders.Invoke("append", header.Key, value); + using (Uint8Array uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: true))) + { + requestObject.SetObjectProperty("body", uint8Buffer); + } } } - if (request.Content != null) + + // Process headers + // Cors has its own restrictions on headers. + // https://developer.mozilla.org/en-US/docs/Web/API/Headers + using (JSObject jsHeaders = new JSObject("Headers")) { - foreach (KeyValuePair> header in request.Content.Headers) + foreach (KeyValuePair> header in request.Headers) { foreach (string value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } + if (request.Content != null) + { + foreach (KeyValuePair> header in request.Content.Headers) + { + foreach (string value in header.Value) + { + jsHeaders.Invoke("append", header.Key, value); + } + } + } + requestObject.SetObjectProperty("headers", jsHeaders); } - requestObject.SetObjectProperty("headers", jsHeaders); - } - JSObject abortController = new JSObject("AbortController"); - using JSObject signal = (JSObject)abortController.GetObjectProperty("signal"); - requestObject.SetObjectProperty("signal", signal); + JSObject abortController = new JSObject("AbortController"); + using JSObject signal = (JSObject)abortController.GetObjectProperty("signal"); + requestObject.SetObjectProperty("signal", signal); - abortRegistration = cancellationToken.Register(() => - { - if (!abortController.IsDisposed) + abortRegistration = cancellationToken.Register(() => + { + if (!abortController.IsDisposed) + { + abortController.Invoke("abort"); + abortController?.Dispose(); + } + }); + + using var args = new System.Runtime.InteropServices.JavaScript.Array(); + if (request.RequestUri != null) { - abortController.Invoke("abort"); - abortController?.Dispose(); + args.Push(request.RequestUri.ToString()); + args.Push(requestObject); } - }); - using var args = new System.Runtime.InteropServices.JavaScript.Array(); - if (request.RequestUri != null) - { - args.Push(request.RequestUri.ToString()); - args.Push(requestObject); - } + var responseTask = s_fetch?.Invoke("apply", s_window, args) as Task; + if (responseTask == null) + throw new Exception(SR.net_http_marshalling_response_promise_from_fetch); - var responseTask = s_fetch?.Invoke("apply", s_window, args) as Task; - if (responseTask == null) - throw new Exception(SR.net_http_marshalling_response_promise_from_fetch); + cancellationToken.ThrowIfCancellationRequested(); - cancellationToken.ThrowIfCancellationRequested(); + var fetchResponseJs = (JSObject)await responseTask.ConfigureAwait(continueOnCapturedContext: true); - var fetchResponseJs = (JSObject)await responseTask.ConfigureAwait(continueOnCapturedContext: true); + var fetchResponse = new WasmFetchResponse(fetchResponseJs, abortController, abortRegistration.Value); + abortRegistration = null; + var responseMessage = new HttpResponseMessage((HttpStatusCode)fetchResponse.Status); + responseMessage.RequestMessage = request; - var fetchResponse = new WasmFetchResponse(fetchResponseJs, abortController, abortRegistration.Value); - abortRegistration = null; - var responseMessage = new HttpResponseMessage((HttpStatusCode)fetchResponse.Status); - responseMessage.RequestMessage = request; + // Here we will set the ReasonPhrase so that it can be evaluated later. + // We do not have a status code but this will signal some type of what happened + // after interrogating the status code for success or not i.e. IsSuccessStatusCode + // + // https://developer.mozilla.org/en-US/docs/Web/API/Response/type + // opaqueredirect: The fetch request was made with redirect: "manual". + // The Response's status is 0, headers are empty, body is null and trailer is empty. + if (fetchResponse.ResponseType == "opaqueredirect") + { + responseMessage.SetReasonPhraseWithoutValidation(fetchResponse.ResponseType); + } - // Here we will set the ReasonPhrase so that it can be evaluated later. - // We do not have a status code but this will signal some type of what happened - // after interrogating the status code for success or not i.e. IsSuccessStatusCode - // - // https://developer.mozilla.org/en-US/docs/Web/API/Response/type - // opaqueredirect: The fetch request was made with redirect: "manual". - // The Response's status is 0, headers are empty, body is null and trailer is empty. - if (fetchResponse.ResponseType == "opaqueredirect") - { - responseMessage.SetReasonPhraseWithoutValidation(fetchResponse.ResponseType); - } + bool streamingEnabled = false; + if (StreamingSupported) + { + request.Options.TryGetValue(EnableStreamingResponse, out streamingEnabled); + } - bool streamingEnabled = false; - if (StreamingSupported) - { - request.Options.TryGetValue(EnableStreamingResponse, out streamingEnabled); - } + responseMessage.Content = streamingEnabled + ? new StreamContent(new WasmHttpReadStream(fetchResponse)) + : new BrowserHttpContent(fetchResponse); - responseMessage.Content = streamingEnabled - ? new StreamContent(new WasmHttpReadStream(fetchResponse)) - : new BrowserHttpContent(fetchResponse); - - // Fill the response headers - // CORS will only allow access to certain headers. - // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. - // cors and basic responses are almost identical except that a cors response restricts the headers you can view to - // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`. - // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types - // - // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation - using (JSObject respHeaders = fetchResponse.Headers) - { - if (respHeaders != null) + // Fill the response headers + // CORS will only allow access to certain headers. + // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. + // cors and basic responses are almost identical except that a cors response restricts the headers you can view to + // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`. + // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types + // + // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation + using (JSObject respHeaders = fetchResponse.Headers) { - using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) + if (respHeaders != null) { - JSObject? nextResult = null; - try + using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) { - nextResult = (JSObject)entriesIterator.Invoke("next"); - while (!(bool)nextResult.GetObjectProperty("done")) + JSObject? nextResult = null; + try { - using (var resultValue = (System.Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value")) + nextResult = (JSObject)entriesIterator.Invoke("next"); + while (!(bool)nextResult.GetObjectProperty("done")) { - var name = (string)resultValue[0]; - var value = (string)resultValue[1]; - if (!responseMessage.Headers.TryAddWithoutValidation(name, value)) - responseMessage.Content.Headers.TryAddWithoutValidation(name, value); + using (var resultValue = (System.Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value")) + { + var name = (string)resultValue[0]; + var value = (string)resultValue[1]; + if (!responseMessage.Headers.TryAddWithoutValidation(name, value)) + responseMessage.Content.Headers.TryAddWithoutValidation(name, value); + } + nextResult?.Dispose(); + nextResult = (JSObject)entriesIterator.Invoke("next"); } + } + finally + { nextResult?.Dispose(); - nextResult = (JSObject)entriesIterator.Invoke("next"); } } - finally - { - nextResult?.Dispose(); - } } } - } - return responseMessage; + return responseMessage; - } - catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) - { - throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); - } - catch (JSException jse) - { - throw TranslateJSException(jse, cancellationToken); - } - finally - { - abortRegistration?.Dispose(); + } + catch (OperationCanceledException oce) when (cancellationToken.IsCancellationRequested) + { + throw CancellationHelper.CreateOperationCanceledException(oce, cancellationToken); + } + catch (JSException jse) + { + throw TranslateJSException(jse, cancellationToken); + } + finally + { + abortRegistration?.Dispose(); + } } } @@ -349,8 +355,11 @@ private sealed class WasmFetchResponse : IDisposable private readonly CancellationTokenRegistration _abortRegistration; private bool _isDisposed; - public WasmFetchResponse(JSObject fetchResponse!!, JSObject abortController!!, CancellationTokenRegistration abortRegistration) + public WasmFetchResponse(JSObject fetchResponse, JSObject abortController, CancellationTokenRegistration abortRegistration) { + ArgumentNullException.ThrowIfNull(fetchResponse); + ArgumentNullException.ThrowIfNull(abortController); + _fetchResponse = fetchResponse; _abortController = abortController; _abortRegistration = abortRegistration; @@ -393,8 +402,10 @@ private sealed class BrowserHttpContent : HttpContent private byte[]? _data; private readonly WasmFetchResponse _status; - public BrowserHttpContent(WasmFetchResponse status!!) + public BrowserHttpContent(WasmFetchResponse status) { + ArgumentNullException.ThrowIfNull(status); + _status = status; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs index 92742ea64afbc5..4440a58b431648 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/ByteArrayContent.cs @@ -14,14 +14,18 @@ public class ByteArrayContent : HttpContent private readonly int _offset; private readonly int _count; - public ByteArrayContent(byte[] content!!) + public ByteArrayContent(byte[] content) { + ArgumentNullException.ThrowIfNull(content); + _content = content; _count = content.Length; } - public ByteArrayContent(byte[] content!!, int offset, int count) + public ByteArrayContent(byte[] content, int offset, int count) { + ArgumentNullException.ThrowIfNull(content); + if ((offset < 0) || (offset > content.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs index c21c4d4db10d39..e1528093db7e32 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs @@ -42,14 +42,18 @@ protected DelegatingHandler(HttpMessageHandler innerHandler) InnerHandler = innerHandler; } - protected internal override HttpResponseMessage Send(HttpRequestMessage request!!, CancellationToken cancellationToken) + protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + SetOperationStarted(); return _innerHandler!.Send(request, cancellationToken); } - protected internal override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) + protected internal override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + SetOperationStarted(); return _innerHandler!.SendAsync(request, cancellationToken); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs index 7c208012eaf18f..16ce1141e2b081 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs @@ -78,6 +78,7 @@ internal override ValueTask SendAsync(HttpRequestMessage re { if (IsEnabled()) { + ArgumentNullException.ThrowIfNull(request); return SendAsyncCore(request, async, cancellationToken); } else @@ -88,8 +89,7 @@ internal override ValueTask SendAsync(HttpRequestMessage re } } - private async ValueTask SendAsyncCore(HttpRequestMessage request!!, bool async, - CancellationToken cancellationToken) + private async ValueTask SendAsyncCore(HttpRequestMessage request, bool async, CancellationToken cancellationToken) { // HttpClientHandler is responsible to call static DiagnosticsHandler.IsEnabled() before forwarding request here. // It will check if propagation is on (because parent Activity exists or there is a listener) or off (forcibly disabled) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs index 43f5102201e7b4..b2c6a3d9d7803d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs @@ -23,8 +23,10 @@ public FormUrlEncodedContent( Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } - private static byte[] GetContentByteArray(IEnumerable> nameValueCollection!!) + private static byte[] GetContentByteArray(IEnumerable> nameValueCollection) { + ArgumentNullException.ThrowIfNull(nameValueCollection); + // Encode and concatenate data StringBuilder builder = new StringBuilder(); foreach (KeyValuePair pair in nameValueCollection) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs index 4d673c25261c33..3e1507e967afb6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaderValueCollection.cs @@ -78,8 +78,10 @@ public bool Contains(T item) return _store.ContainsParsedValue(_descriptor, item); } - public void CopyTo(T[] array!!, int arrayIndex) + public void CopyTo(T[] array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + // Allow arrayIndex == array.Length in case our own collection is empty if ((arrayIndex < 0) || (arrayIndex > array.Length)) { @@ -178,8 +180,10 @@ public override string ToString() return _store.GetHeaderString(_descriptor); } - private void CheckValue(T item!!) + private void CheckValue(T item) { + ArgumentNullException.ThrowIfNull(item); + if (_descriptor.Parser == GenericHeaderParser.TokenListParser) { // The collection expects valid HTTP tokens, which are typed as string. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs index 1510bb42496d9a..46af69825aa5b0 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs @@ -95,8 +95,10 @@ internal void Add(HeaderDescriptor descriptor, string? value) public void Add(string name, IEnumerable values) => Add(GetHeaderDescriptor(name), values); - internal void Add(HeaderDescriptor descriptor, IEnumerable values!!) + internal void Add(HeaderDescriptor descriptor, IEnumerable values) { + ArgumentNullException.ThrowIfNull(values); + PrepareHeaderInfoForAdd(descriptor, out HeaderStoreItemInfo info, out bool addToStore); try @@ -162,8 +164,10 @@ public bool TryAddWithoutValidation(string name, IEnumerable values) => TryGetHeaderDescriptor(name, out HeaderDescriptor descriptor) && TryAddWithoutValidation(descriptor, values); - internal bool TryAddWithoutValidation(HeaderDescriptor descriptor, IEnumerable values!!) + internal bool TryAddWithoutValidation(HeaderDescriptor descriptor, IEnumerable values) { + ArgumentNullException.ThrowIfNull(values); + using IEnumerator enumerator = values.GetEnumerator(); if (enumerator.MoveNext()) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs index 713e94a64eb2a5..31376a4de20f58 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs @@ -9,8 +9,9 @@ namespace System.Net.Http.Headers { internal sealed class UnvalidatedObjectCollection : ObjectCollection where T : class { - public override void Validate(T item!!) + public override void Validate(T item) { + ArgumentNullException.ThrowIfNull(item); } } @@ -192,7 +193,11 @@ internal sealed class DebugView { private readonly ObjectCollection _collection; - public DebugView(ObjectCollection collection!!) => _collection = collection; + public DebugView(ObjectCollection collection) + { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; + } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs index 773d8658767a2b..2e52dbd7f1911d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs @@ -26,8 +26,10 @@ public ProductInfoHeaderValue(string productName, string? productVersion) { } - public ProductInfoHeaderValue(ProductHeaderValue product!!) + public ProductInfoHeaderValue(ProductHeaderValue product) { + ArgumentNullException.ThrowIfNull(product); + _product = product; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs index 97e3a591cc2a87..168bb3388441d2 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeConditionHeaderValue.cs @@ -26,8 +26,10 @@ public RangeConditionHeaderValue(DateTimeOffset date) _date = date; } - public RangeConditionHeaderValue(EntityTagHeaderValue entityTag!!) + public RangeConditionHeaderValue(EntityTagHeaderValue entityTag) { + ArgumentNullException.ThrowIfNull(entityTag); + _entityTag = entityTag; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs index a67eaf3726b2c8..2abf393e39d9e1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs @@ -558,8 +558,10 @@ async Task Core( } } - private void CheckRequestBeforeSend(HttpRequestMessage request!!) + private void CheckRequestBeforeSend(HttpRequestMessage request) { + ArgumentNullException.ThrowIfNull(request); + CheckDisposed(); CheckRequestMessage(request); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs index 643d0f110f555f..53a71d1a333922 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs @@ -20,8 +20,10 @@ public HttpMessageInvoker(HttpMessageHandler handler) { } - public HttpMessageInvoker(HttpMessageHandler handler!!, bool disposeHandler) + public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler) { + ArgumentNullException.ThrowIfNull(handler); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, handler); _handler = handler; @@ -29,8 +31,10 @@ public HttpMessageInvoker(HttpMessageHandler handler!!, bool disposeHandler) } [UnsupportedOSPlatformAttribute("browser")] - public virtual HttpResponseMessage Send(HttpRequestMessage request!!, CancellationToken cancellationToken) + public virtual HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + CheckDisposed(); if (ShouldSendWithTelemetry(request)) @@ -57,8 +61,10 @@ public virtual HttpResponseMessage Send(HttpRequestMessage request!!, Cancellati } } - public virtual Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) + public virtual Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + CheckDisposed(); if (ShouldSendWithTelemetry(request)) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs index 44f31d76112e2e..479ce771ad343b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRequestMessage.cs @@ -120,8 +120,10 @@ public HttpRequestMessage() { } - public HttpRequestMessage(HttpMethod method!!, Uri? requestUri) + public HttpRequestMessage(HttpMethod method, Uri? requestUri) { + ArgumentNullException.ThrowIfNull(method); + // It's OK to have a 'null' request Uri. If HttpClient is used, the 'BaseAddress' will be added. // If there is no 'BaseAddress', sending this request message will throw. // Note that we also allow the string to be empty: null and empty are considered equivalent. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs index 0d08eb6141115c..8c50087e6d59d1 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MessageProcessingHandler.cs @@ -27,9 +27,11 @@ protected abstract HttpRequestMessage ProcessRequest(HttpRequestMessage request, protected abstract HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken); - protected internal sealed override HttpResponseMessage Send(HttpRequestMessage request!!, + protected internal sealed override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + // Since most of the SendAsync code is just Task handling, there's no reason to share the code. HttpRequestMessage newRequestMessage = ProcessRequest(request, cancellationToken); HttpResponseMessage response = base.Send(newRequestMessage, cancellationToken); @@ -37,9 +39,11 @@ protected internal sealed override HttpResponseMessage Send(HttpRequestMessage r return newResponseMessage; } - protected internal sealed override Task SendAsync(HttpRequestMessage request!!, + protected internal sealed override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + // ProcessRequest() and ProcessResponse() are supposed to be fast, so we call ProcessRequest() on the same // thread SendAsync() was invoked to avoid context switches. However, if ProcessRequest() throws, we have // to catch the exception since the caller doesn't expect exceptions when calling SendAsync(): The diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs index d9ed3613a1dca7..6bbff7ba2d872f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs @@ -108,8 +108,10 @@ private static string GetDefaultBoundary() return Guid.NewGuid().ToString(); } - public virtual void Add(HttpContent content!!) + public virtual void Add(HttpContent content) { + ArgumentNullException.ThrowIfNull(content); + _nestedContent.Add(content); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs index e4206d4d65ef54..7eba9d8aee7660 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartFormDataContent.cs @@ -23,15 +23,19 @@ public MultipartFormDataContent(string boundary) { } - public override void Add(HttpContent content!!) + public override void Add(HttpContent content) { + ArgumentNullException.ThrowIfNull(content); + content.Headers.ContentDisposition ??= new ContentDispositionHeaderValue(formData); base.Add(content); } - public void Add(HttpContent content!!, string name) + public void Add(HttpContent content, string name) { + ArgumentNullException.ThrowIfNull(content); + if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(name)); @@ -40,8 +44,10 @@ public void Add(HttpContent content!!, string name) AddInternal(content, name, null); } - public void Add(HttpContent content!!, string name, string fileName) + public void Add(HttpContent content, string name, string fileName) { + ArgumentNullException.ThrowIfNull(content); + if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(name)); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs index 17e9e7664658d6..261ee3d17b4c1a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs @@ -33,9 +33,11 @@ private Stream ConsumeStream() return _stream; } - protected override void SerializeToStream(Stream stream!!, TransportContext? context, + protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(stream); + using (Stream contentStream = ConsumeStream()) { const int BufferSize = 8192; @@ -46,12 +48,18 @@ protected override void SerializeToStream(Stream stream!!, TransportContext? con protected sealed override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => SerializeToStreamAsync(stream, context, CancellationToken.None); - protected sealed override async Task SerializeToStreamAsync(Stream stream!!, TransportContext? context, CancellationToken cancellationToken) + protected sealed override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - using (Stream contentStream = ConsumeStream()) + ArgumentNullException.ThrowIfNull(stream); + return Impl(stream, context, cancellationToken); + + async Task Impl(Stream stream, TransportContext? context, CancellationToken cancellationToken) { - const int BufferSize = 8192; - await contentStream.CopyToAsync(stream, BufferSize, cancellationToken).ConfigureAwait(false); + using (Stream contentStream = ConsumeStream()) + { + const int BufferSize = 8192; + await contentStream.CopyToAsync(stream, BufferSize, cancellationToken).ConfigureAwait(false); + } } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs index eef5f2d4c7964b..e9729cc6f36534 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs @@ -111,8 +111,10 @@ private static Uri GetProxyUri(string scheme, CFProxy proxy) return null; } - public bool IsBypassed(Uri targetUri!!) + public bool IsBypassed(Uri targetUri) { + ArgumentNullException.ThrowIfNull(targetUri); + Uri? proxyUri = GetProxy(targetUri); return Equals(proxyUri, targetUri) || proxyUri == null; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs index eb9e62b30b61d7..3c82fa87a66a83 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs @@ -531,9 +531,11 @@ private HttpMessageHandlerStage SetupHandlerChain() return _handler; } - protected internal override HttpResponseMessage Send(HttpRequestMessage request!!, + protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + if (request.Version.Major >= 2) { throw new NotSupportedException(SR.Format(SR.net_http_http2_sync_not_supported, GetType())); @@ -560,8 +562,10 @@ protected internal override HttpResponseMessage Send(HttpRequestMessage request! return handler.Send(request, cancellationToken); } - protected internal override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) + protected internal override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request); + CheckDisposed(); if (cancellationToken.IsCancellationRequested) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs index 6a33a01b17ee64..8be52a024a95b7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/StreamContent.cs @@ -17,14 +17,18 @@ public class StreamContent : HttpContent private bool _contentConsumed; private long _start; - public StreamContent(Stream content!!) + public StreamContent(Stream content) { + ArgumentNullException.ThrowIfNull(content); + // Indicate that we should use default buffer size by setting size to 0. InitializeContent(content, 0); } - public StreamContent(Stream content!!, int bufferSize) + public StreamContent(Stream content, int bufferSize) { + ArgumentNullException.ThrowIfNull(content); + if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize)); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs index 262e49e7070a60..b597408f5b36b3 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/StringContent.cs @@ -42,8 +42,10 @@ public StringContent(string content, Encoding? encoding, MediaTypeHeaderValue me // A StringContent is essentially a ByteArrayContent. We serialize the string into a byte-array in the // constructor using encoding information provided by the caller (if any). When this content is sent, the // Content-Length can be retrieved easily (length of the array). - private static byte[] GetContentByteArray(string content!!, Encoding? encoding) + private static byte[] GetContentByteArray(string content, Encoding? encoding) { + ArgumentNullException.ThrowIfNull(content); + // In this case we treat 'null' strings different from string.Empty in order to be consistent with our // other *Content constructors: 'null' throws, empty values are allowed. diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs index cee7d986e669e4..4cb267978cc508 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs @@ -102,8 +102,10 @@ public HttpListenerPrefixCollection Prefixes } } - internal void AddPrefix(string uriPrefix!!) + internal void AddPrefix(string uriPrefix) { + ArgumentNullException.ThrowIfNull(uriPrefix); + string? registeredPrefix; try { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index 3a0aeccc0b3581..39bdde21e34130 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -205,8 +205,10 @@ public void AppendHeader(string name, string value) Headers.Add(name, value); } - public void AppendCookie(Cookie cookie!!) + public void AppendCookie(Cookie cookie) { + ArgumentNullException.ThrowIfNull(cookie); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"cookie: {cookie}"); Cookies.Add(cookie); } @@ -268,8 +270,10 @@ public void Redirect([StringSyntax(StringSyntaxAttribute.Uri)] string url) StatusDescription = HttpStatusDescription.Get(StatusCode)!; } - public void SetCookie(Cookie cookie!!) + public void SetCookie(Cookie cookie) { + ArgumentNullException.ThrowIfNull(cookie); + Cookie newCookie = cookie.Clone(); int added = Cookies.InternalAdd(newCookie, true); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs index be93b1248605da..498ae36fd65707 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs @@ -149,8 +149,10 @@ private void OnRead(IAsyncResult base_ares) } } - public override int EndRead(IAsyncResult asyncResult!!) + public override int EndRead(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + HttpStreamAsyncResult? ares = asyncResult as HttpStreamAsyncResult; if (ares == null || !ReferenceEquals(this, ares._parent)) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index 3a9129933d2be0..aa1f0ee2ae3700 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -392,8 +392,10 @@ private IAsyncResult BeginGetClientCertificateCore(AsyncCallback? requestCallbac return asyncResult; } - public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult!!) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + GetClientCertificateAsyncResult? clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs index ce6056af78a872..12e44700cd1679 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs @@ -161,8 +161,10 @@ protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size return _stream.BeginRead(buffer, offset, size, cback, state); } - public override int EndRead(IAsyncResult asyncResult!!) + public override int EndRead(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + if (asyncResult is HttpStreamAsyncResult r) { if (!ReferenceEquals(this, r._parent)) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index 146dddd69af97c..2176ccd58e20c1 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -252,8 +252,10 @@ internal void SetClientCertificateError(int clientCertificateError) _clientCertificateError = clientCertificateError; } - public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult!!) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + X509Certificate2? clientCertificate = null; ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs index 76da09f7976701..0991741e40093a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs @@ -162,8 +162,10 @@ private static unsafe ulong SendWebSocketHeaders(HttpListenerResponse response) true); } - internal static void ValidateInnerStream(Stream innerStream!!) + internal static void ValidateInnerStream(Stream innerStream) { + ArgumentNullException.ThrowIfNull(innerStream); + if (!innerStream.CanRead) { throw new ArgumentException(SR.net_writeonlystream, nameof(innerStream)); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs b/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs index eaeaecc6cc0401..321b88ef99bbe0 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs @@ -156,13 +156,17 @@ internal int EncodeBytes(byte[] buffer, int offset, int count, bool dontDeferFin public string GetEncodedString() => _encoder.GetEncodedString(); - public override int EndRead(IAsyncResult asyncResult!!) + public override int EndRead(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + return ReadAsyncResult.End(asyncResult); } - public override void EndWrite(IAsyncResult asyncResult!!) + public override void EndWrite(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + WriteAsyncResult.End(asyncResult); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs b/src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs index c5533daf552485..d2321b3dfe2c56 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs @@ -11,8 +11,10 @@ internal abstract class DelegatedStream : Stream { private readonly Stream _stream; - protected DelegatedStream(Stream stream!!) + protected DelegatedStream(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + _stream = stream; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs index a8c67d806ac942..aa8430f9b8fa1b 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs @@ -82,8 +82,10 @@ internal void SetContentFromFile(string fileName, string? mediaType) _part.SetContent(stream, null, mediaType); } - internal void SetContentFromString(string content!!, ContentType? contentType) + internal void SetContentFromString(string content, ContentType? contentType) { + ArgumentNullException.ThrowIfNull(content); + _part.Stream?.Close(); Encoding encoding; @@ -116,8 +118,10 @@ internal void SetContentFromString(string content!!, ContentType? contentType) } } - internal void SetContentFromString(string content!!, Encoding? encoding, string? mediaType) + internal void SetContentFromString(string content, Encoding? encoding, string? mediaType) { + ArgumentNullException.ThrowIfNull(content); + _part.Stream?.Close(); if (string.IsNullOrEmpty(mediaType)) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressCollection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressCollection.cs index d3ccf39ae51643..5496f0a43978ea 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressCollection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddressCollection.cs @@ -23,13 +23,17 @@ public void Add(string addresses) ParseValue(addresses); } - protected override void SetItem(int index, MailAddress item!!) + protected override void SetItem(int index, MailAddress item) { + ArgumentNullException.ThrowIfNull(item); + base.SetItem(index, item); } - protected override void InsertItem(int index, MailAddress item!!) + protected override void InsertItem(int index, MailAddress item) { + ArgumentNullException.ThrowIfNull(item); + base.InsertItem(index, item); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs index cb4c835eb4556e..70d844575ead30 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs @@ -52,8 +52,11 @@ public MailMessage(string from, string to, string? subject, string? body) : this } - public MailMessage(MailAddress from!!, MailAddress to!!) + public MailMessage(MailAddress from, MailAddress to) { + ArgumentNullException.ThrowIfNull(from); + ArgumentNullException.ThrowIfNull(to); + _message = new Message(from, to); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs index 0a47725f7f8dcc..0744a29bb99b4b 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs @@ -296,8 +296,10 @@ internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allow } } - internal void EndSend(IAsyncResult asyncResult!!) + internal void EndSend(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + if (Content != null) { Content.EndSend(asyncResult); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs index 914087cee23f87..86e0943d540548 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs @@ -22,8 +22,10 @@ internal MailWriter(Stream stream, bool encodeForTransport) { } - internal override void WriteHeaders(NameValueCollection headers!!, bool allowUnicode) + internal override void WriteHeaders(NameValueCollection headers, bool allowUnicode) { + ArgumentNullException.ThrowIfNull(headers); + foreach (string key in headers) { string[] values = headers!.GetValues(key)!; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpAuthenticationManager.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpAuthenticationManager.cs index d9b82ea30390df..0cbe1faef60458 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpAuthenticationManager.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpAuthenticationManager.cs @@ -18,8 +18,10 @@ static SmtpAuthenticationManager() Register(new SmtpLoginAuthenticationModule()); } - internal static void Register(ISmtpAuthenticationModule module!!) + internal static void Register(ISmtpAuthenticationModule module) { + ArgumentNullException.ThrowIfNull(module); + lock (s_modules) { s_modules.Add(module); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index 423896e0b82ab5..25ec53cfe795f4 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -413,8 +413,10 @@ public void Send(string from, string recipients, string? subject, string? body) Send(mailMessage); } - public void Send(MailMessage message!!) + public void Send(MailMessage message) { + ArgumentNullException.ThrowIfNull(message); + ObjectDisposedException.ThrowIf(_disposed, this); if (NetEventSource.Log.IsEnabled()) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpFailedRecipientsException.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpFailedRecipientsException.cs index a9f115a72e1e9c..11cadf451887cc 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpFailedRecipientsException.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpFailedRecipientsException.cs @@ -34,17 +34,21 @@ protected SmtpFailedRecipientsException(SerializationInfo info, StreamingContext _innerExceptions = (SmtpFailedRecipientException[])info.GetValue("innerExceptions", typeof(SmtpFailedRecipientException[]))!; } - public SmtpFailedRecipientsException(string? message, SmtpFailedRecipientException[] innerExceptions!!) : + public SmtpFailedRecipientsException(string? message, SmtpFailedRecipientException[] innerExceptions) : base(message, innerExceptions.Length > 0 ? innerExceptions[0].FailedRecipient : null, innerExceptions.Length > 0 ? innerExceptions[0] : null) { + ArgumentNullException.ThrowIfNull(innerExceptions); + _innerExceptions = innerExceptions == null ? Array.Empty() : innerExceptions; } - internal SmtpFailedRecipientsException(List innerExceptions!!, bool allFailed) : + internal SmtpFailedRecipientsException(List innerExceptions, bool allFailed) : base(allFailed ? SR.SmtpAllRecipientsFailed : SR.SmtpRecipientFailed, innerExceptions.Count > 0 ? innerExceptions[0].FailedRecipient : null, innerExceptions.Count > 0 ? innerExceptions[0] : null) { + ArgumentNullException.ThrowIfNull(innerExceptions); + _innerExceptions = innerExceptions.ToArray(); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs index d906af286f355e..e06de7affa2e93 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs @@ -29,8 +29,10 @@ internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManag { } - internal SmtpTransport(SmtpClient client, ISmtpAuthenticationModule[] authenticationModules!!) + internal SmtpTransport(SmtpClient client, ISmtpAuthenticationModule[] authenticationModules) { + ArgumentNullException.ThrowIfNull(authenticationModules); + _client = client; _authenticationModules = authenticationModules; } @@ -144,9 +146,12 @@ internal static void EndGetConnection(IAsyncResult result) SmtpConnection.EndGetConnection(result); } - internal IAsyncResult BeginSendMail(MailAddress sender!!, MailAddressCollection recipients!!, + internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, bool allowUnicode, AsyncCallback? callback, object? state) { + ArgumentNullException.ThrowIfNull(sender); + ArgumentNullException.ThrowIfNull(recipients); + SendMailAsyncResult result = new SendMailAsyncResult(_connection!, sender, recipients, allowUnicode, _connection!.DSNEnabled ? deliveryNotify : null, callback, state); @@ -185,9 +190,12 @@ internal static MailWriter EndSendMail(IAsyncResult result) } } - internal MailWriter SendMail(MailAddress sender!!, MailAddressCollection recipients!!, string deliveryNotify, + internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, bool allowUnicode, out SmtpFailedRecipientException? exception) { + ArgumentNullException.ThrowIfNull(sender); + ArgumentNullException.ThrowIfNull(recipients); + MailCommand.Send(_connection!, SmtpCommands.Mail, sender, allowUnicode); _failedRecipientExceptions.Clear(); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs index 2998c9ff4226ba..10cd4a1a953a09 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs @@ -26,8 +26,10 @@ internal abstract class BaseWriter protected Stream _contentStream = null!; // set to null on dispose protected bool _isInContent; - protected BaseWriter(Stream stream!!, bool shouldEncodeLeadingDots) + protected BaseWriter(Stream stream, bool shouldEncodeLeadingDots) { + ArgumentNullException.ThrowIfNull(stream); + _stream = stream; _shouldEncodeLeadingDots = shouldEncodeLeadingDots; _onCloseHandler = new EventHandler(OnClose); @@ -39,8 +41,11 @@ protected BaseWriter(Stream stream!!, bool shouldEncodeLeadingDots) internal abstract void WriteHeaders(NameValueCollection headers, bool allowUnicode); - internal void WriteHeader(string name!!, string value!!, bool allowUnicode) + internal void WriteHeader(string name, string value, bool allowUnicode) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + if (_isInContent) { throw new InvalidOperationException(SR.MailWriterIsInContent); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs index a9deebd85519a3..5d72c47d81f12f 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs @@ -54,8 +54,10 @@ public ContentDisposition() // no need to parse disposition since there's nothing to parse } - public ContentDisposition(string disposition!!) + public ContentDisposition(string disposition) { + ArgumentNullException.ThrowIfNull(disposition); + _isChanged = true; _disposition = disposition; ParseValue(); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs index 627777531c1aaf..005f9969e92e4f 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs @@ -107,8 +107,10 @@ internal static string DecodeHeaderValue(string? value) return Encoding.GetEncoding(charSet); } - internal static bool IsAscii(string value!!, bool permitCROrLF) + internal static bool IsAscii(string value, bool permitCROrLF) { + ArgumentNullException.ThrowIfNull(value); + foreach (char c in value) { if (c > 0x7f) @@ -215,8 +217,10 @@ internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callba throw new NotImplementedException(); } - internal void EndSend(IAsyncResult asyncResult!!) + internal void EndSend(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + LazyAsyncResult? castedAsyncResult = asyncResult as MimePartAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs index 0c8095a03f8a5b..cf00bba73797b3 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs @@ -101,8 +101,10 @@ internal TransferEncoding TransferEncoding } } - internal void SetContent(Stream stream!!) + internal void SetContent(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + if (_streamSet) { _stream!.Close(); @@ -114,8 +116,10 @@ internal void SetContent(Stream stream!!) TransferEncoding = TransferEncoding.Base64; } - internal void SetContent(Stream stream!!, string? name, string? mimeType) + internal void SetContent(Stream stream, string? name, string? mimeType) { + ArgumentNullException.ThrowIfNull(stream); + if (mimeType != null && mimeType != string.Empty) { _contentType = new ContentType(mimeType); @@ -127,8 +131,10 @@ internal void SetContent(Stream stream!!, string? name, string? mimeType) SetContent(stream); } - internal void SetContent(Stream stream!!, ContentType? contentType) + internal void SetContent(Stream stream, ContentType? contentType) { + ArgumentNullException.ThrowIfNull(stream); + _contentType = contentType; SetContent(stream); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs index 19b444795cdc05..de84d4c28e6dc1 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs @@ -19,14 +19,18 @@ internal sealed class MimeWriter : BaseWriter private readonly byte[] _boundaryBytes; private bool _writeBoundary = true; - internal MimeWriter(Stream stream, string boundary!!) + internal MimeWriter(Stream stream, string boundary) : base(stream, false) // Unnecessary, the underlying MailWriter stream already encodes dots { + ArgumentNullException.ThrowIfNull(boundary); + _boundaryBytes = Encoding.ASCII.GetBytes(boundary); } - internal override void WriteHeaders(NameValueCollection headers!!, bool allowUnicode) + internal override void WriteHeaders(NameValueCollection headers, bool allowUnicode) { + ArgumentNullException.ThrowIfNull(headers); + foreach (string key in headers) WriteHeader(key, headers[key]!, allowUnicode); } diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs index 784f30187248fe..df8b7e4d6f0e75 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs @@ -36,8 +36,10 @@ public static string GetHostName() return name; } - public static IPHostEntry GetHostEntry(IPAddress address!!) + public static IPHostEntry GetHostEntry(IPAddress address) { + ArgumentNullException.ThrowIfNull(address); + if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(address, $"Invalid address '{address}'"); @@ -61,8 +63,10 @@ public static IPHostEntry GetHostEntry(string hostNameOrAddress) => /// /// An instance that contains the address information about the host specified in . /// - public static IPHostEntry GetHostEntry(string hostNameOrAddress!!, AddressFamily family) + public static IPHostEntry GetHostEntry(string hostNameOrAddress, AddressFamily family) { + ArgumentNullException.ThrowIfNull(hostNameOrAddress); + // See if it's an IP Address. IPHostEntry ipHostEntry; if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address)) @@ -142,8 +146,10 @@ public static Task GetHostEntryAsync(string hostNameOrAddress, Addr } } - public static Task GetHostEntryAsync(IPAddress address!!) + public static Task GetHostEntryAsync(IPAddress address) { + ArgumentNullException.ThrowIfNull(address); + if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(address, $"Invalid address '{address}'"); @@ -163,8 +169,12 @@ public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback? r public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback? requestCallback, object? stateObject) => TaskToApm.Begin(GetHostEntryAsync(hostNameOrAddress), requestCallback, stateObject); - public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult!!) => - TaskToApm.End(asyncResult); + public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) + { + ArgumentNullException.ThrowIfNull(asyncResult); + + return TaskToApm.End(asyncResult); + } public static IPAddress[] GetHostAddresses(string hostNameOrAddress) => GetHostAddresses(hostNameOrAddress, AddressFamily.Unspecified); @@ -177,8 +187,10 @@ public static IPAddress[] GetHostAddresses(string hostNameOrAddress) /// /// An array of type that holds the IP addresses for the host that is specified by the parameter. /// - public static IPAddress[] GetHostAddresses(string hostNameOrAddress!!, AddressFamily family) + public static IPAddress[] GetHostAddresses(string hostNameOrAddress, AddressFamily family) { + ArgumentNullException.ThrowIfNull(hostNameOrAddress); + // See if it's an IP Address. IPAddress[] addresses; if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address)) @@ -231,12 +243,18 @@ public static Task GetHostAddressesAsync(string hostNameOrAddress, public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback? requestCallback, object? state) => TaskToApm.Begin(GetHostAddressesAsync(hostNameOrAddress), requestCallback, state); - public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult!!) => - TaskToApm.End(asyncResult); + public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) + { + ArgumentNullException.ThrowIfNull(asyncResult); + + return TaskToApm.End(asyncResult); + } [Obsolete("GetHostByName has been deprecated. Use GetHostEntry instead.")] - public static IPHostEntry GetHostByName(string hostName!!) + public static IPHostEntry GetHostByName(string hostName) { + ArgumentNullException.ThrowIfNull(hostName); + if (IPAddress.TryParse(hostName, out IPAddress? address)) { return CreateHostEntryForAddress(address); @@ -250,12 +268,18 @@ public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback? re TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: true, throwOnIIPAny: true, AddressFamily.Unspecified, CancellationToken.None), requestCallback, stateObject); [Obsolete("EndGetHostByName has been deprecated. Use EndGetHostEntry instead.")] - public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult!!) => - TaskToApm.End(asyncResult); + public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult) + { + ArgumentNullException.ThrowIfNull(asyncResult); + + return TaskToApm.End(asyncResult); + } [Obsolete("GetHostByAddress has been deprecated. Use GetHostEntry instead.")] - public static IPHostEntry GetHostByAddress(string address!!) + public static IPHostEntry GetHostByAddress(string address) { + ArgumentNullException.ThrowIfNull(address); + IPHostEntry ipHostEntry = GetHostEntryCore(IPAddress.Parse(address), AddressFamily.Unspecified); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry); @@ -263,8 +287,10 @@ public static IPHostEntry GetHostByAddress(string address!!) } [Obsolete("GetHostByAddress has been deprecated. Use GetHostEntry instead.")] - public static IPHostEntry GetHostByAddress(IPAddress address!!) + public static IPHostEntry GetHostByAddress(IPAddress address) { + ArgumentNullException.ThrowIfNull(address); + IPHostEntry ipHostEntry = GetHostEntryCore(address, AddressFamily.Unspecified); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry); @@ -272,8 +298,10 @@ public static IPHostEntry GetHostByAddress(IPAddress address!!) } [Obsolete("Resolve has been deprecated. Use GetHostEntry instead.")] - public static IPHostEntry Resolve(string hostName!!) + public static IPHostEntry Resolve(string hostName) { + ArgumentNullException.ThrowIfNull(hostName); + // See if it's an IP Address. IPHostEntry ipHostEntry; if (IPAddress.TryParse(hostName, out IPAddress? address) && @@ -468,8 +496,10 @@ private static Task GetHostEntryCoreAsync(string hostName, bool jus (Task)GetHostEntryOrAddressesCoreAsync(hostName, justReturnParsedIp, throwOnIIPAny, justAddresses: false, family, cancellationToken); // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned. - private static Task GetHostEntryOrAddressesCoreAsync(string hostName!!, bool justReturnParsedIp, bool throwOnIIPAny, bool justAddresses, AddressFamily family, CancellationToken cancellationToken) + private static Task GetHostEntryOrAddressesCoreAsync(string hostName, bool justReturnParsedIp, bool throwOnIIPAny, bool justAddresses, AddressFamily family, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(hostName); + if (cancellationToken.IsCancellationRequested) { return justAddresses ? (Task) diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs index ae305f43ff052b..3bfd0ab797d2d1 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs @@ -65,8 +65,10 @@ private void OnSerializing(StreamingContext context) m_version = m_list.Count; } - public void Add(Cookie cookie!!) + public void Add(Cookie cookie) { + ArgumentNullException.ThrowIfNull(cookie); + int idx = IndexOf(cookie); if (idx == -1) { @@ -78,8 +80,10 @@ public void Add(Cookie cookie!!) } } - public void Add(CookieCollection cookies!!) + public void Add(CookieCollection cookies) { + ArgumentNullException.ThrowIfNull(cookies); + foreach (Cookie? cookie in cookies.m_list) { Add(cookie!); diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index 324b5bf28b1311..d61dfaea829a68 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -216,8 +216,10 @@ public int PerDomainCapacity } // This method will construct a faked URI: the Domain property is required for param. - public void Add(Cookie cookie!!) + public void Add(Cookie cookie) { + ArgumentNullException.ThrowIfNull(cookie); + if (cookie.Domain.Length == 0) { throw new ArgumentException( @@ -575,8 +577,10 @@ private static int ExpireCollection(CookieCollection cc) } } - public void Add(CookieCollection cookies!!) + public void Add(CookieCollection cookies) { + ArgumentNullException.ThrowIfNull(cookies); + foreach (Cookie c in (ICollection)cookies) { Add(c); @@ -651,8 +655,10 @@ internal bool IsLocalDomain(string host) return false; } - public void Add(Uri uri!!, Cookie cookie!!) + public void Add(Uri uri, Cookie cookie) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(cookie); Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), m_fqdnMyDomain, true, true); @@ -660,8 +666,11 @@ public void Add(Uri uri!!, Cookie cookie!!) Add(new_cookie, true); } - public void Add(Uri uri!!, CookieCollection cookies!!) + public void Add(Uri uri, CookieCollection cookies) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(cookies); + bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { @@ -753,8 +762,10 @@ internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCo return cookies; } - public CookieCollection GetCookies(Uri uri!!) + public CookieCollection GetCookies(Uri uri) { + ArgumentNullException.ThrowIfNull(uri); + return InternalGetCookies(uri) ?? new CookieCollection(); } @@ -985,8 +996,10 @@ private void MergeUpdateCollections(ref CookieCollection? destination, CookieCol } } - public string GetCookieHeader(Uri uri!!) + public string GetCookieHeader(Uri uri) { + ArgumentNullException.ThrowIfNull(uri); + return GetCookieHeader(uri, out _); } @@ -1019,8 +1032,10 @@ internal string GetCookieHeader(Uri uri, out string optCookie2) return StringBuilderCache.GetStringAndRelease(builder); } - public void SetCookies(Uri uri!!, string cookieHeader!!) + public void SetCookies(Uri uri, string cookieHeader) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(cookieHeader); CookieCutter(uri, null, cookieHeader, true); // Will throw on error } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs index af7f89cce55abd..5369513e48a1b7 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -21,8 +21,11 @@ public CredentialCache() { } - public void Add(Uri uriPrefix!!, string authType!!, NetworkCredential cred) + public void Add(Uri uriPrefix, string authType, NetworkCredential cred) { + ArgumentNullException.ThrowIfNull(uriPrefix); + ArgumentNullException.ThrowIfNull(authType); + if ((cred is SystemNetworkCredential) && !((string.Equals(authType, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase)) || (string.Equals(authType, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase)) @@ -132,8 +135,11 @@ public void Remove(string? host, int port, string? authenticationType) _cacheForHosts.Remove(key); } - public NetworkCredential? GetCredential(Uri uriPrefix!!, string authType!!) + public NetworkCredential? GetCredential(Uri uriPrefix, string authType) { + ArgumentNullException.ThrowIfNull(uriPrefix); + ArgumentNullException.ThrowIfNull(authType); + if (_cache == null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null."); diff --git a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs index 3cf2510e315ed4..3c83d86213bc14 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs @@ -231,8 +231,10 @@ public static bool TryParse(ReadOnlySpan ipSpan, [NotNullWhen(true)] out I return (address != null); } - public static IPAddress Parse(string ipString!!) + public static IPAddress Parse(string ipString) { + ArgumentNullException.ThrowIfNull(ipString); + return IPAddressParser.Parse(ipString.AsSpan(), tryParse: false)!; } @@ -409,8 +411,10 @@ public static short NetworkToHostOrder(short network) return HostToNetworkOrder(network); } - public static bool IsLoopback(IPAddress address!!) + public static bool IsLoopback(IPAddress address) { + ArgumentNullException.ThrowIfNull(address); + if (address.IsIPv6) { // Do Equals test for IPv6 addresses diff --git a/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs b/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs index 04bdfec675b967..3e1d27a9dcfd78 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs @@ -44,8 +44,10 @@ public IPEndPoint(long address, int port) /// /// Creates a new instance of the IPEndPoint class with the specified address and port. /// - public IPEndPoint(IPAddress address!!, int port) + public IPEndPoint(IPAddress address, int port) { + ArgumentNullException.ThrowIfNull(address); + if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -125,8 +127,10 @@ public static bool TryParse(ReadOnlySpan s, [NotNullWhen(true)] out IPEndP return false; } - public static IPEndPoint Parse(string s!!) + public static IPEndPoint Parse(string s) { + ArgumentNullException.ThrowIfNull(s); + return Parse(s.AsSpan()); } @@ -148,8 +152,10 @@ public override string ToString() public override SocketAddress Serialize() => new SocketAddress(Address, Port); - public override EndPoint Create(SocketAddress socketAddress!!) + public override EndPoint Create(SocketAddress socketAddress) { + ArgumentNullException.ThrowIfNull(socketAddress); + if (socketAddress.Family != AddressFamily) { throw new ArgumentException(SR.Format(SR.net_InvalidAddressFamily, socketAddress.Family.ToString(), GetType().FullName, AddressFamily.ToString()), nameof(socketAddress)); diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs index 5ccb653f7b9938..c55dac26cafc43 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockConnection.cs @@ -48,8 +48,10 @@ internal long? ConnectionError internal override X509Certificate? RemoteCertificate => null; // Constructor for outbound connections - internal MockConnection(EndPoint remoteEndPoint!!, SslClientAuthenticationOptions? sslClientAuthenticationOptions, IPEndPoint? localEndPoint = null, int maxUnidirectionalStreams = 100, int maxBidirectionalStreams = 100) + internal MockConnection(EndPoint remoteEndPoint, SslClientAuthenticationOptions? sslClientAuthenticationOptions, IPEndPoint? localEndPoint = null, int maxUnidirectionalStreams = 100, int maxBidirectionalStreams = 100) { + ArgumentNullException.ThrowIfNull(remoteEndPoint); + IPEndPoint ipEndPoint = GetIPEndPoint(remoteEndPoint); if (ipEndPoint.Address != IPAddress.Loopback) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs b/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs index dc25c363e4a0f0..af7bbc5e6b8ddb 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs @@ -22,16 +22,19 @@ private AuthenticationManager() { } public static Authorization? PreAuthenticate(WebRequest request, ICredentials credentials) => throw new PlatformNotSupportedException(); - public static void Register(IAuthenticationModule authenticationModule!!) + public static void Register(IAuthenticationModule authenticationModule) { + ArgumentNullException.ThrowIfNull(authenticationModule); } - public static void Unregister(IAuthenticationModule authenticationModule!!) + public static void Unregister(IAuthenticationModule authenticationModule) { + ArgumentNullException.ThrowIfNull(authenticationModule); } - public static void Unregister(string authenticationScheme!!) + public static void Unregister(string authenticationScheme) { + ArgumentNullException.ThrowIfNull(authenticationScheme); } public static IEnumerator RegisteredModules => Array.Empty().GetEnumerator(); diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 8d818e54631485..7921f5f60cb414 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -683,11 +683,12 @@ public override IAsyncResult BeginGetResponse(AsyncCallback? callback, object? s /// /// Returns result of query for the Response of an FTP request [async version] /// - public override WebResponse EndGetResponse(IAsyncResult asyncResult!!) + public override WebResponse EndGetResponse(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + try { - // parameter validation LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { @@ -803,8 +804,10 @@ public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, obje return asyncResult; } - public override Stream EndGetRequestStream(IAsyncResult asyncResult!!) + public override Stream EndGetRequestStream(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + Stream? requestStream; try { diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs index f2306722da3c14..afd49930d688c4 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -1430,8 +1430,10 @@ public void AddRange(string rangeSpecifier, int from, int to) AddRange(rangeSpecifier, (long)from, (long)to); } - public void AddRange(string rangeSpecifier!!, long from, long to) + public void AddRange(string rangeSpecifier, long from, long to) { + ArgumentNullException.ThrowIfNull(rangeSpecifier); + if ((from < 0) || (to < 0)) { throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall); @@ -1455,8 +1457,10 @@ public void AddRange(string rangeSpecifier, int range) AddRange(rangeSpecifier, (long)range); } - public void AddRange(string rangeSpecifier!!, long range) + public void AddRange(string rangeSpecifier, long range) { + ArgumentNullException.ThrowIfNull(rangeSpecifier); + if (!HttpValidationHelpers.IsValidToken(rangeSpecifier)) { throw new ArgumentException(SR.net_nottoken, nameof(rangeSpecifier)); diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs index 46f1dad764929e..80d18184ea93ba 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs @@ -145,8 +145,10 @@ private static WebRequest Create(Uri requestUri, bool useUriBase) // Returns: // Newly created WebRequest. [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static WebRequest Create(string requestUriString!!) + public static WebRequest Create(string requestUriString) { + ArgumentNullException.ThrowIfNull(requestUriString); + return Create(new Uri(requestUriString), false); } @@ -161,8 +163,10 @@ public static WebRequest Create(string requestUriString!!) // Returns: // Newly created WebRequest. [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static WebRequest Create(Uri requestUri!!) + public static WebRequest Create(Uri requestUri) { + ArgumentNullException.ThrowIfNull(requestUri); + return Create(requestUri, false); } @@ -178,20 +182,26 @@ public static WebRequest Create(Uri requestUri!!) // Returns: // Newly created WebRequest. [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static WebRequest CreateDefault(Uri requestUri!!) + public static WebRequest CreateDefault(Uri requestUri) { + ArgumentNullException.ThrowIfNull(requestUri); + return Create(requestUri, true); } [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static HttpWebRequest CreateHttp(string requestUriString!!) + public static HttpWebRequest CreateHttp(string requestUriString) { + ArgumentNullException.ThrowIfNull(requestUriString); + return CreateHttp(new Uri(requestUriString)); } [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static HttpWebRequest CreateHttp(Uri requestUri!!) + public static HttpWebRequest CreateHttp(Uri requestUri) { + ArgumentNullException.ThrowIfNull(requestUri); + if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https")) { throw new NotSupportedException(SR.net_unknown_prefix); @@ -216,8 +226,11 @@ public static HttpWebRequest CreateHttp(Uri requestUri!!) // // Returns: // True if the registration worked, false otherwise. - public static bool RegisterPrefix(string prefix!!, IWebRequestCreate creator!!) + public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(creator); + bool Error = false; int i; WebRequestPrefixElement Current; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs index d5a7477870cbac..a8abf29bf5922d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicy.cs @@ -13,8 +13,10 @@ public sealed partial class CipherSuitesPolicy internal CipherSuitesPolicyPal Pal { get; private set; } [CLSCompliant(false)] - public CipherSuitesPolicy(IEnumerable allowedCipherSuites!!) + public CipherSuitesPolicy(IEnumerable allowedCipherSuites) { + ArgumentNullException.ThrowIfNull(allowedCipherSuites); + Pal = new CipherSuitesPolicyPal(allowedCipherSuites); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs index 6ab268953ad55a..f218ce2875128f 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs @@ -39,13 +39,13 @@ internal SslApplicationProtocol(byte[] protocol, bool copy) protocol; } - public SslApplicationProtocol(byte[] protocol!!) : - this(protocol, copy: true) + public SslApplicationProtocol(byte[] protocol) : + this(protocol ?? throw new ArgumentNullException(nameof(protocol)), copy: true) { } - public SslApplicationProtocol(string protocol!!) : - this(s_utf8.GetBytes(protocol), copy: false) + public SslApplicationProtocol(string protocol) : + this(s_utf8.GetBytes(protocol ?? throw new ArgumentNullException(nameof(protocol))), copy: false) { } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs index 80062232fdacc4..f4816110f918de 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs @@ -408,8 +408,10 @@ public virtual void AuthenticateAsClient(string targetHost, X509CertificateColle AuthenticateAsClient(options); } - public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions!!) + public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions) { + ArgumentNullException.ThrowIfNull(sslClientAuthenticationOptions); + SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); @@ -441,8 +443,10 @@ public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool AuthenticateAsServer(options); } - public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions!!) + public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions) { + ArgumentNullException.ThrowIfNull(sslServerAuthenticationOptions); + SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); @@ -469,8 +473,10 @@ public virtual Task AuthenticateAsClientAsync(string targetHost, X509Certificate return AuthenticateAsClientAsync(options); } - public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions!!, CancellationToken cancellationToken = default) + public Task AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(sslClientAuthenticationOptions); + SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); @@ -519,8 +525,10 @@ public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, return AuthenticateAsServerAsync(options); } - public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions!!, CancellationToken cancellationToken = default) + public Task AuthenticateAsServerAsync(SslServerAuthenticationOptions sslServerAuthenticationOptions, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(sslServerAuthenticationOptions); + SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs index fcf018951d725c..32e8a3d70d62ad 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs @@ -12,8 +12,10 @@ namespace System.Security.Authentication.ExtendedProtection { public class ServiceNameCollection : ReadOnlyCollectionBase { - public ServiceNameCollection(ICollection items!!) + public ServiceNameCollection(ICollection items) { + ArgumentNullException.ThrowIfNull(items); + // Normalize and filter for duplicates. AddIfNew(items, expectStrings: true); } diff --git a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs index 4d244976958777..1013bbcd4d2f2e 100644 --- a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs +++ b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs @@ -113,8 +113,10 @@ public static int DnsRefreshTimeout public static ServicePoint FindServicePoint(string uriString, IWebProxy? proxy) => FindServicePoint(new Uri(uriString), proxy); [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static ServicePoint FindServicePoint(Uri address!!, IWebProxy? proxy) + public static ServicePoint FindServicePoint(Uri address, IWebProxy? proxy) { + ArgumentNullException.ThrowIfNull(address); + // If there's a proxy for this address, get the "real" address. bool isProxyServicePoint = ProxyAddressIfNecessary(ref address, proxy); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs index 3229ac80db62f1..a94a642dd2c1dc 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/MulticastOption.cs @@ -12,14 +12,19 @@ public class MulticastOption // Creates a new instance of the MulticastOption class with the specified IP address // group and local address. - public MulticastOption(IPAddress group!!, IPAddress mcint!!) + public MulticastOption(IPAddress group, IPAddress mcint) { + ArgumentNullException.ThrowIfNull(group); + ArgumentNullException.ThrowIfNull(mcint); + _group = group; LocalAddress = mcint; } - public MulticastOption(IPAddress group!!, int interfaceIndex) + public MulticastOption(IPAddress group, int interfaceIndex) { + ArgumentNullException.ThrowIfNull(group); + if (interfaceIndex < 0 || interfaceIndex > 0x00FFFFFF) { throw new ArgumentOutOfRangeException(nameof(interfaceIndex)); @@ -30,8 +35,10 @@ public MulticastOption(IPAddress group!!, int interfaceIndex) } // Creates a new version of the MulticastOption class for the specified group. - public MulticastOption(IPAddress group!!) + public MulticastOption(IPAddress group) { + ArgumentNullException.ThrowIfNull(group); + _group = group; LocalAddress = IPAddress.Any; @@ -83,8 +90,10 @@ public class IPv6MulticastOption // Creates a new instance of the MulticaseOption class with the specified IP // address group and local address. - public IPv6MulticastOption(IPAddress group!!, long ifindex) + public IPv6MulticastOption(IPAddress group, long ifindex) { + ArgumentNullException.ThrowIfNull(group); + if (ifindex < 0 || ifindex > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException(nameof(ifindex)); @@ -96,8 +105,10 @@ public IPv6MulticastOption(IPAddress group!!, long ifindex) // Creates a new version of the MulticastOption class for the specified // group. - public IPv6MulticastOption(IPAddress group!!) + public IPv6MulticastOption(IPAddress group) { + ArgumentNullException.ThrowIfNull(group); + _group = group; InterfaceIndex = 0; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs index a99318ba5b8f56..23b2883a702fc1 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/NetworkStream.cs @@ -41,8 +41,10 @@ public NetworkStream(Socket socket, FileAccess access) { } - public NetworkStream(Socket socket!!, FileAccess access, bool ownsSocket) + public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) { + ArgumentNullException.ThrowIfNull(socket); + if (!socket.Blocking) { // Stream.Read*/Write* are incompatible with the semantics of non-blocking sockets, and diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs index 1346fc48756b67..97a8567222ef3f 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SendPacketsElement.cs @@ -25,8 +25,10 @@ public SendPacketsElement(string filepath, long offset, int count) : this(filepath, offset, count, false) { } - public SendPacketsElement(string filepath!!, long offset, int count, bool endOfPacket) + public SendPacketsElement(string filepath, long offset, int count, bool endOfPacket) { + ArgumentNullException.ThrowIfNull(filepath); + // The native API will validate the file length on send. if (offset < 0) { @@ -49,8 +51,10 @@ public SendPacketsElement(FileStream fileStream, long offset, int count) : this(fileStream, offset, count, false) { } - public SendPacketsElement(FileStream fileStream!!, long offset, int count, bool endOfPacket) + public SendPacketsElement(FileStream fileStream, long offset, int count, bool endOfPacket) { + ArgumentNullException.ThrowIfNull(fileStream); + if (!fileStream.IsAsync) { throw new ArgumentException(SR.net_sockets_sendpackelement_FileStreamMustBeAsync, nameof(fileStream)); @@ -77,8 +81,10 @@ public SendPacketsElement(byte[] buffer, int offset, int count) : this(buffer, offset, count, false) { } - public SendPacketsElement(byte[] buffer!!, int offset, int count, bool endOfPacket) + public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { + ArgumentNullException.ThrowIfNull(buffer); + if ((uint)offset > (uint)buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs index f688288d8dde0a..536006bb7534e9 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs @@ -235,8 +235,10 @@ async ValueTask Core(IPAddress[] addresses, int port, CancellationToken cancella /// The port on the remote host to connect to. /// A cancellation token that can be used to cancel the asynchronous operation. /// An asynchronous task that completes when the connection is established. - public ValueTask ConnectAsync(string host!!, int port, CancellationToken cancellationToken) + public ValueTask ConnectAsync(string host, int port, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(host); + EndPoint ep = IPAddress.TryParse(host, out IPAddress? parsedAddress) ? (EndPoint) new IPEndPoint(parsedAddress, port) : new DnsEndPoint(host, port); @@ -618,8 +620,10 @@ public ValueTask SendToAsync(ReadOnlyMemory buffer, EndPoint remoteEP /// The remote host to which to send the data. /// A cancellation token that can be used to cancel the asynchronous operation. /// An asynchronous task that completes with the number of bytes sent. - public ValueTask SendToAsync(ReadOnlyMemory buffer, SocketFlags socketFlags, EndPoint remoteEP!!, CancellationToken cancellationToken = default) + public ValueTask SendToAsync(ReadOnlyMemory buffer, SocketFlags socketFlags, EndPoint remoteEP, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(remoteEP); + if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); @@ -726,8 +730,10 @@ public ValueTask SendFileAsync(string? fileName, ReadOnlyMemory preBuffer, return saea.SendPacketsAsync(this, cancellationToken); } - private static void ValidateBufferArguments(byte[] buffer!!, int offset, int size) + private static void ValidateBufferArguments(byte[] buffer, int offset, int size) { + ArgumentNullException.ThrowIfNull(buffer); + if ((uint)offset > (uint)buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); @@ -753,8 +759,10 @@ private static void ValidateBuffer(ArraySegment buffer) } /// Validates the supplied buffer list, throwing if it's null or empty. - private static void ValidateBuffersList(IList> buffers!!) + private static void ValidateBuffersList(IList> buffers) { + ArgumentNullException.ThrowIfNull(buffers); + if (buffers.Count == 0) { throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers)); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index db3fbaeab7a689..552b50e732e98e 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -232,9 +232,17 @@ private unsafe Socket(SafeSocketHandle handle, bool loadPropertiesFromHandle) } } - private static SafeSocketHandle ValidateHandle(SafeSocketHandle handle!!) => - handle.IsInvalid ? throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)) : - handle; + private static SafeSocketHandle ValidateHandle(SafeSocketHandle handle) + { + ArgumentNullException.ThrowIfNull(handle); + + if (handle.IsInvalid) + { + throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); + } + + return handle; + } // // Properties @@ -989,8 +997,6 @@ public void Listen(int backlog) // Creates a new Sockets.Socket instance to handle an incoming connection. public Socket Accept() { - // Validate input parameters. - ThrowIfDisposed(); if (_rightEndPoint == null) @@ -2144,7 +2150,6 @@ public bool Poll(TimeSpan timeout, SelectMode mode) => // Determines the status of a socket. public static void Select(IList? checkRead, IList? checkWrite, IList? checkError, int microSeconds) { - // Validate input parameters. if ((checkRead == null || checkRead.Count == 0) && (checkWrite == null || checkWrite.Count == 0) && (checkError == null || checkError.Count == 0)) @@ -2502,7 +2507,6 @@ public Socket EndAccept(IAsyncResult asyncResult) // There's no direct equivalent of this in the Task APIs, so we mimic it here. private async Task<(Socket s, byte[] buffer, int bytesReceived)> AcceptAndReceiveHelperAsync(Socket? acceptSocket, int receiveSize) { - // Validate input parameters. if (receiveSize < 0) { throw new ArgumentOutOfRangeException(nameof(receiveSize)); @@ -2736,8 +2740,10 @@ internal bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket, bool saeaCan return pending; } - public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e!!) + public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e) { + ArgumentNullException.ThrowIfNull(e); + if (e.HasMultipleBuffers) { throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); @@ -2778,8 +2784,10 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType /// Binds an unbound socket to "any" if necessary to support a connect. partial void WildcardBindForConnectIfNecessary(AddressFamily addressFamily); - public static void CancelConnectAsync(SocketAsyncEventArgs e!!) + public static void CancelConnectAsync(SocketAsyncEventArgs e) { + ArgumentNullException.ThrowIfNull(e); + e.CancelConnectAsync(); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs index 576b44bc67339d..f85af2ed9386b1 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPClient.cs @@ -32,10 +32,7 @@ public TcpClient(AddressFamily family) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, family); - // Validate parameter - if (family != AddressFamily.InterNetwork && - family != AddressFamily.InterNetworkV6 && - family != AddressFamily.Unknown) + if (family is not (AddressFamily.InterNetwork or AddressFamily.InterNetworkV6 or AddressFamily.Unknown)) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family)); } @@ -45,8 +42,10 @@ public TcpClient(AddressFamily family) } // Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point. - public TcpClient(IPEndPoint localEP!!) + public TcpClient(IPEndPoint localEP) { + ArgumentNullException.ThrowIfNull(localEP); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP); _family = localEP.AddressFamily; // set before calling CreateSocket InitializeClientSocket(); @@ -55,8 +54,10 @@ public TcpClient(IPEndPoint localEP!!) // Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on // the specified host. - public TcpClient(string hostname!!, int port) + public TcpClient(string hostname, int port) { + ArgumentNullException.ThrowIfNull(hostname); + if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, hostname); if (!TcpValidationHelpers.ValidatePortNumber(port)) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs index 747f72752516a7..dc737f4a4d983b 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs @@ -28,7 +28,6 @@ public UdpClient() : this(AddressFamily.InterNetwork) // Initializes a new instance of the System.Net.Sockets.UdpClientclass. public UdpClient(AddressFamily family) { - // Validate the address family. if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "UDP"), nameof(family)); @@ -53,13 +52,10 @@ public UdpClient(int port) : this(port, AddressFamily.InterNetwork) // specified port number. public UdpClient(int port, AddressFamily family) { - // Validate input parameters. if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); } - - // Validate the address family. if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6) { throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "UDP"), nameof(family)); @@ -84,8 +80,10 @@ public UdpClient(int port, AddressFamily family) // Creates a new instance of the UdpClient class that communicates on the // specified end point. - public UdpClient(IPEndPoint localEP!!) + public UdpClient(IPEndPoint localEP) { + ArgumentNullException.ThrowIfNull(localEP); + // IPv6 Changes: Set the AddressFamily of this object before // creating the client socket. _family = localEP.AddressFamily; @@ -358,21 +356,14 @@ private void ValidateDatagram(byte[] datagram, int bytes, IPEndPoint? endPoint) public IAsyncResult BeginReceive(AsyncCallback? requestCallback, object? state) { - // Validate input parameters. ThrowIfDisposed(); // Due to the nature of the ReceiveFrom() call and the ref parameter convention, // we need to cast an IPEndPoint to its base class EndPoint and cast it back down // to IPEndPoint. - EndPoint tempRemoteEP; - if (_family == AddressFamily.InterNetwork) - { - tempRemoteEP = IPEndPointStatics.Any; - } - else - { - tempRemoteEP = IPEndPointStatics.IPv6Any; - } + EndPoint tempRemoteEP = _family == AddressFamily.InterNetwork ? + IPEndPointStatics.Any : + IPEndPointStatics.IPv6Any; return _clientSocket.BeginReceiveFrom(_buffer, 0, MaxUDPSize, SocketFlags.None, ref tempRemoteEP, requestCallback, state); } @@ -381,15 +372,9 @@ public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint? remoteEP) { ThrowIfDisposed(); - EndPoint tempRemoteEP; - if (_family == AddressFamily.InterNetwork) - { - tempRemoteEP = IPEndPointStatics.Any; - } - else - { - tempRemoteEP = IPEndPointStatics.IPv6Any; - } + EndPoint tempRemoteEP = _family == AddressFamily.InterNetwork ? + IPEndPointStatics.Any : + IPEndPointStatics.IPv6Any; int received = _clientSocket.EndReceiveFrom(asyncResult, ref tempRemoteEP); remoteEP = (IPEndPoint)tempRemoteEP; @@ -409,36 +394,28 @@ public byte[] EndReceive(IAsyncResult asyncResult, ref IPEndPoint? remoteEP) // Joins a multicast address group. public void JoinMulticastGroup(IPAddress multicastAddr) { - // Validate input parameters. ThrowIfDisposed(); ArgumentNullException.ThrowIfNull(multicastAddr); - - // IPv6 Changes: we need to create the correct MulticastOption and - // must also check for address family compatibility. - // Note: we cannot reliably use IPv4 multicast over IPv6 in DualMode - // as such we keep the compatibility explicit between IP stack versions if (multicastAddr.AddressFamily != _family) { + // For IPv6, we need to create the correct MulticastOption and must also check for address family compatibility. + // Note: we cannot reliably use IPv4 multicast over IPv6 in DualMode, as such we keep the compatibility explicit between IP stack versions throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), nameof(multicastAddr)); } if (_family == AddressFamily.InterNetwork) { - MulticastOption mcOpt = new MulticastOption(multicastAddr); - _clientSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, - mcOpt); + new MulticastOption(multicastAddr)); } else { - IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr); - _clientSocket.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, - mcOpt); + new IPv6MulticastOption(multicastAddr)); } } @@ -446,18 +423,15 @@ public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress) { ThrowIfDisposed(); - // Validate input parameters. if (_family != AddressFamily.InterNetwork) { throw new SocketException((int)SocketError.OperationNotSupported); } - MulticastOption mcOpt = new MulticastOption(multicastAddr, localAddress); - _clientSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, - mcOpt); + new MulticastOption(multicastAddr, localAddress)); } // Joins an IPv6 multicast address group. @@ -465,27 +439,22 @@ public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr) { ThrowIfDisposed(); - // Validate input parameters. ArgumentNullException.ThrowIfNull(multicastAddr); - if (ifindex < 0) { throw new ArgumentException(SR.net_value_cannot_be_negative, nameof(ifindex)); } - - // Ensure that this is an IPv6 client, otherwise throw WinSock - // Operation not supported socked exception. if (_family != AddressFamily.InterNetworkV6) { + // Ensure that this is an IPv6 client, otherwise throw WinSock + // Operation not supported socked exception. throw new SocketException((int)SocketError.OperationNotSupported); } - IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex); - _clientSocket.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, - mcOpt); + new IPv6MulticastOption(multicastAddr, ifindex)); } // Joins a multicast address group with the specified time to live (TTL). @@ -493,7 +462,6 @@ public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive) { ThrowIfDisposed(); - // parameter validation; ArgumentNullException.ThrowIfNull(multicastAddr); if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255)) { @@ -515,33 +483,26 @@ public void DropMulticastGroup(IPAddress multicastAddr) { ThrowIfDisposed(); - // Validate input parameters. ArgumentNullException.ThrowIfNull(multicastAddr); - - // IPv6 Changes: we need to create the correct MulticastOption and - // must also check for address family compatibility. if (multicastAddr.AddressFamily != _family) { + // For IPv6, we need to create the correct MulticastOption and must also check for address family compatibility. throw new ArgumentException(SR.Format(SR.net_protocol_invalid_multicast_family, "UDP"), nameof(multicastAddr)); } if (_family == AddressFamily.InterNetwork) { - MulticastOption mcOpt = new MulticastOption(multicastAddr); - _clientSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.DropMembership, - mcOpt); + new MulticastOption(multicastAddr)); } else { - IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr); - _clientSocket.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.DropMembership, - mcOpt); + new IPv6MulticastOption(multicastAddr)); } } @@ -550,27 +511,21 @@ public void DropMulticastGroup(IPAddress multicastAddr, int ifindex) { ThrowIfDisposed(); - // Validate input parameters. ArgumentNullException.ThrowIfNull(multicastAddr); - if (ifindex < 0) { throw new ArgumentException(SR.net_value_cannot_be_negative, nameof(ifindex)); } - - // Ensure that this is an IPv6 client, otherwise throw WinSock - // Operation not supported socked exception. if (_family != AddressFamily.InterNetworkV6) { + // Ensure that this is an IPv6 client. throw new SocketException((int)SocketError.OperationNotSupported); } - IPv6MulticastOption mcOpt = new IPv6MulticastOption(multicastAddr, ifindex); - _clientSocket.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.DropMembership, - mcOpt); + new IPv6MulticastOption(multicastAddr, ifindex)); } public Task SendAsync(byte[] datagram, int bytes) => @@ -902,22 +857,13 @@ public byte[] Receive([NotNull] ref IPEndPoint? remoteEP) // this is a fix due to the nature of the ReceiveFrom() call and the // ref parameter convention, we need to cast an IPEndPoint to it's base // class EndPoint and cast it back down to IPEndPoint. ugly but it works. - // - EndPoint tempRemoteEP; - - if (_family == AddressFamily.InterNetwork) - { - tempRemoteEP = IPEndPointStatics.Any; - } - else - { - tempRemoteEP = IPEndPointStatics.IPv6Any; - } + EndPoint tempRemoteEP = _family == AddressFamily.InterNetwork ? + IPEndPointStatics.Any : + IPEndPointStatics.IPv6Any; int received = Client.ReceiveFrom(_buffer, MaxUDPSize, 0, ref tempRemoteEP); remoteEP = (IPEndPoint)tempRemoteEP; - // because we don't return the actual length, we need to ensure the returned buffer // has the appropriate length. diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs index 060012e96967ea..fef2bc711409f7 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UdpReceiveResult.cs @@ -18,8 +18,11 @@ public struct UdpReceiveResult : IEquatable /// /// A buffer for data to receive in the UDP packet /// The remote endpoint of the UDP packet - public UdpReceiveResult(byte[] buffer!!, IPEndPoint remoteEndPoint!!) + public UdpReceiveResult(byte[] buffer, IPEndPoint remoteEndPoint) { + ArgumentNullException.ThrowIfNull(buffer); + ArgumentNullException.ThrowIfNull(remoteEndPoint); + _buffer = buffer; _remoteEndPoint = remoteEndPoint; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs index b69e6d82965b24..de3558da694fdc 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.cs @@ -22,8 +22,10 @@ public UnixDomainSocketEndPoint(string path) : this(path, null) { } - private UnixDomainSocketEndPoint(string path!!, string? boundFileName) + private UnixDomainSocketEndPoint(string path, string? boundFileName) { + ArgumentNullException.ThrowIfNull(path); + BoundFileName = boundFileName; // Pathname socket addresses should be null-terminated. @@ -56,8 +58,10 @@ private UnixDomainSocketEndPoint(string path!!, string? boundFileName) internal static int MaxAddressSize => s_nativeAddressSize; - internal UnixDomainSocketEndPoint(SocketAddress socketAddress!!) + internal UnixDomainSocketEndPoint(SocketAddress socketAddress) { + ArgumentNullException.ThrowIfNull(socketAddress); + if (socketAddress.Family != EndPointAddressFamily || socketAddress.Size > s_nativeAddressSize) { diff --git a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs index c597c50beb5e97..24c700e76658e8 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -278,8 +278,10 @@ private async Task GetWebResponseTaskAsync(WebRequest request) public byte[] DownloadData(string address) => DownloadData(GetUri(address)); - public byte[] DownloadData(Uri address!!) + public byte[] DownloadData(Uri address) { + ArgumentNullException.ThrowIfNull(address); + StartOperation(); try { @@ -316,8 +318,11 @@ private byte[] DownloadDataInternal(Uri address, out WebRequest request) public void DownloadFile(string address, string fileName) => DownloadFile(GetUri(address), fileName); - public void DownloadFile(Uri address!!, string fileName!!) + public void DownloadFile(Uri address, string fileName) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(fileName); + WebRequest? request = null; FileStream? fs = null; bool succeeded = false; @@ -352,8 +357,10 @@ public void DownloadFile(Uri address!!, string fileName!!) public Stream OpenRead(string address) => OpenRead(GetUri(address)); - public Stream OpenRead(Uri address!!) + public Stream OpenRead(Uri address) { + ArgumentNullException.ThrowIfNull(address); + WebRequest? request = null; StartOperation(); try @@ -383,8 +390,10 @@ public Stream OpenWrite(Uri address) => public Stream OpenWrite(string address, string? method) => OpenWrite(GetUri(address), method); - public Stream OpenWrite(Uri address!!, string? method) + public Stream OpenWrite(Uri address, string? method) { + ArgumentNullException.ThrowIfNull(address); + method ??= MapToDefaultMethod(address); WebRequest? request = null; @@ -419,8 +428,11 @@ public byte[] UploadData(Uri address, byte[] data) => public byte[] UploadData(string address, string? method, byte[] data) => UploadData(GetUri(address), method, data); - public byte[] UploadData(Uri address!!, string? method, byte[] data!!) + public byte[] UploadData(Uri address, string? method, byte[] data) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(data); + method ??= MapToDefaultMethod(address); StartOperation(); @@ -535,8 +547,11 @@ public byte[] UploadFile(Uri address, string fileName) => public byte[] UploadFile(string address, string? method, string fileName) => UploadFile(GetUri(address), method, fileName); - public byte[] UploadFile(Uri address!!, string? method, string fileName!!) + public byte[] UploadFile(Uri address, string? method, string fileName) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(fileName); + method ??= MapToDefaultMethod(address); FileStream? fs = null; @@ -603,8 +618,11 @@ public byte[] UploadValues(Uri address, NameValueCollection data) => public byte[] UploadValues(string address, string? method, NameValueCollection data) => UploadValues(GetUri(address), method, data); - public byte[] UploadValues(Uri address!!, string? method, NameValueCollection data!!) + public byte[] UploadValues(Uri address, string? method, NameValueCollection data) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(data); + method ??= MapToDefaultMethod(address); WebRequest? request = null; @@ -637,8 +655,11 @@ public string UploadString(Uri address, string data) => public string UploadString(string address, string? method, string data) => UploadString(GetUri(address), method, data); - public string UploadString(Uri address!!, string? method, string data!!) + public string UploadString(Uri address, string? method, string data) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(data); + method ??= MapToDefaultMethod(address); StartOperation(); @@ -658,8 +679,10 @@ public string UploadString(Uri address!!, string? method, string data!!) public string DownloadString(string address) => DownloadString(GetUri(address)); - public string DownloadString(Uri address!!) + public string DownloadString(Uri address) { + ArgumentNullException.ThrowIfNull(address); + StartOperation(); try { @@ -746,8 +769,10 @@ private void CopyHeadersTo(WebRequest request) } } - private Uri GetUri(string address!!) + private Uri GetUri(string address) { + ArgumentNullException.ThrowIfNull(address); + Uri? uri; if (_baseAddress != null) { @@ -764,8 +789,10 @@ private Uri GetUri(string address!!) return GetUri(uri); } - private Uri GetUri(Uri address!!) + private Uri GetUri(Uri address) { + ArgumentNullException.ThrowIfNull(address); + Uri? uri = address; if (!address.IsAbsoluteUri && _baseAddress != null && !Uri.TryCreate(_baseAddress, address, out uri)) @@ -1258,8 +1285,10 @@ private void InvokeOperationCompleted(AsyncOperation asyncOp, SendOrPostCallback public void OpenReadAsync(Uri address) => OpenReadAsync(address, null); - public void OpenReadAsync(Uri address!!, object? userToken) + public void OpenReadAsync(Uri address, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + AsyncOperation asyncOp = StartAsyncOperation(userToken); try { @@ -1294,8 +1323,10 @@ public void OpenWriteAsync(Uri address) => public void OpenWriteAsync(Uri address, string? method) => OpenWriteAsync(address, method, null); - public void OpenWriteAsync(Uri address!!, string? method, object? userToken) + public void OpenWriteAsync(Uri address, string? method, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); @@ -1351,8 +1382,10 @@ private void DownloadStringAsyncCallback(byte[]? returnBytes, Exception? excepti public void DownloadStringAsync(Uri address) => DownloadStringAsync(address, null); - public void DownloadStringAsync(Uri address!!, object? userToken) + public void DownloadStringAsync(Uri address, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + AsyncOperation asyncOp = StartAsyncOperation(userToken); try { @@ -1375,8 +1408,10 @@ private void DownloadDataAsyncCallback(byte[]? returnBytes, Exception? exception public void DownloadDataAsync(Uri address) => DownloadDataAsync(address, null); - public void DownloadDataAsync(Uri address!!, object? userToken) + public void DownloadDataAsync(Uri address, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + AsyncOperation asyncOp = StartAsyncOperation(userToken); try { @@ -1399,8 +1434,11 @@ private void DownloadFileAsyncCallback(byte[]? returnBytes, Exception? exception public void DownloadFileAsync(Uri address, string fileName) => DownloadFileAsync(address, fileName, null); - public void DownloadFileAsync(Uri address!!, string fileName!!, object? userToken) + public void DownloadFileAsync(Uri address, string fileName, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(fileName); + FileStream? fs = null; AsyncOperation asyncOp = StartAsyncOperation(userToken); try @@ -1422,8 +1460,11 @@ public void UploadStringAsync(Uri address, string data) => public void UploadStringAsync(Uri address, string? method, string data) => UploadStringAsync(address, method, data, null); - public void UploadStringAsync(Uri address!!, string? method, string data!!, object? userToken) + public void UploadStringAsync(Uri address, string? method, string data, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(data); + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); @@ -1468,8 +1509,11 @@ public void UploadDataAsync(Uri address, byte[] data) => public void UploadDataAsync(Uri address, string? method, byte[] data) => UploadDataAsync(address, method, data, null); - public void UploadDataAsync(Uri address!!, string? method, byte[] data!!, object? userToken) + public void UploadDataAsync(Uri address, string? method, byte[] data, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(data); + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); @@ -1504,8 +1548,11 @@ public void UploadFileAsync(Uri address, string fileName) => public void UploadFileAsync(Uri address, string? method, string fileName) => UploadFileAsync(address, method, fileName, null); - public void UploadFileAsync(Uri address!!, string? method, string fileName!!, object? userToken) + public void UploadFileAsync(Uri address, string? method, string fileName, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(fileName); + method ??= MapToDefaultMethod(address); FileStream? fs = null; @@ -1538,8 +1585,11 @@ public void UploadValuesAsync(Uri address, NameValueCollection data) => public void UploadValuesAsync(Uri address, string? method, NameValueCollection data) => UploadValuesAsync(address, method, data, null); - public void UploadValuesAsync(Uri address!!, string? method, NameValueCollection data!!, object? userToken) + public void UploadValuesAsync(Uri address, string? method, NameValueCollection data, object? userToken) { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(data); + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); diff --git a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs index 195fe6979961ed..690bb9a6b28d4e 100644 --- a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs +++ b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs @@ -92,8 +92,10 @@ public bool UseDefaultCredentials set => Credentials = value ? CredentialCache.DefaultCredentials : null; } - public Uri? GetProxy(Uri destination!!) + public Uri? GetProxy(Uri destination) { + ArgumentNullException.ThrowIfNull(destination); + return IsBypassed(destination) ? destination : Address; } @@ -171,8 +173,10 @@ private bool IsMatchInBypassList(Uri input) return false; } - public bool IsBypassed(Uri host!!) + public bool IsBypassed(Uri host) { + ArgumentNullException.ThrowIfNull(host); + return Address == null || (BypassProxyOnLocal && IsLocal(host)) || diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs index 1db846074a6446..5905497a6f911f 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs @@ -50,8 +50,10 @@ public override WebSocketState State } } - public Task ConnectAsync(Uri uri!!, CancellationToken cancellationToken) + public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(uri); + if (!uri.IsAbsoluteUri) { throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri)); diff --git a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs index 0627dca37a8c71..2d9ff208ada16a 100644 --- a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs +++ b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocket.cs @@ -138,8 +138,10 @@ public static ArraySegment CreateServerBuffer(int receiveBufferSize) /// The agreed upon sub-protocol that was used when creating the connection. /// The keep-alive interval to use, or to disable keep-alives. /// The created . - public static WebSocket CreateFromStream(Stream stream!!, bool isServer, string? subProtocol, TimeSpan keepAliveInterval) + public static WebSocket CreateFromStream(Stream stream, bool isServer, string? subProtocol, TimeSpan keepAliveInterval) { + ArgumentNullException.ThrowIfNull(stream); + if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(stream)); @@ -163,8 +165,11 @@ public static WebSocket CreateFromStream(Stream stream!!, bool isServer, string? /// Creates a that operates on a representing a web socket connection. /// The for the connection. /// The options with which the websocket must be created. - public static WebSocket CreateFromStream(Stream stream!!, WebSocketCreationOptions options!!) + public static WebSocket CreateFromStream(Stream stream, WebSocketCreationOptions options) { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(options); + if (!stream.CanRead || !stream.CanWrite) throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(stream)); @@ -185,10 +190,12 @@ public static void RegisterPrefixes() } [EditorBrowsable(EditorBrowsableState.Never)] - public static WebSocket CreateClientWebSocket(Stream innerStream!!, + public static WebSocket CreateClientWebSocket(Stream innerStream, string? subProtocol, int receiveBufferSize, int sendBufferSize, TimeSpan keepAliveInterval, bool useZeroMaskingKey, ArraySegment internalBuffer) { + ArgumentNullException.ThrowIfNull(innerStream); + if (!innerStream.CanRead || !innerStream.CanWrite) { throw new ArgumentException(!innerStream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(innerStream)); diff --git a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs index 88a46e604acd56..d5426cc74571c7 100644 --- a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs +++ b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/DenseTensor.cs @@ -100,8 +100,13 @@ public override void SetValue(int index, T value) Buffer.Span[index] = value; } - protected override void CopyTo(T[] array!!, int arrayIndex) + protected override void CopyTo(T[] array, int arrayIndex) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Length < arrayIndex + Length) { throw new ArgumentException(SR.NumberGreaterThenAvailableSpace, nameof(array)); diff --git a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs index cb31580bc9d9cd..4ca56a3b479e06 100644 --- a/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs +++ b/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/Tensor.cs @@ -308,8 +308,13 @@ protected Tensor(ReadOnlySpan dimensions, bool reverseStride) /// /// Array from which to derive dimensions. /// False (default) to indicate that the first dimension is most major (farthest apart) and the last dimension is most minor (closest together): akin to row-major in a rank-2 tensor. True to indicate that the last dimension is most major (farthest apart) and the first dimension is most minor (closest together): akin to column-major in a rank-2 tensor. - protected Tensor(Array fromArray!!, bool reverseStride) + protected Tensor(Array fromArray, bool reverseStride) { + if (fromArray is null) + { + throw new ArgumentNullException(nameof(fromArray)); + } + if (fromArray.Rank == 0) { throw new ArgumentException(SR.ArrayMustContainElements, nameof(fromArray)); @@ -631,16 +636,26 @@ private Tensor GetTriangle(int offset, bool upper) /// /// A one-dimensional array of integers that represent the indices specifying the position of the element to get. /// The value at the specified position in this Tensor. - public virtual T this[params int[] indices!!] + public virtual T this[params int[] indices] { get { + if (indices is null) + { + throw new ArgumentNullException(nameof(indices)); + } + var span = new ReadOnlySpan(indices); return this[span]; } set { + if (indices is null) + { + throw new ArgumentNullException(nameof(indices)); + } + var span = new ReadOnlySpan(indices); this[span] = value; } @@ -917,8 +932,13 @@ void ICollection.CopyTo(T[] array, int arrayIndex) /// /// The zero-based index in array at which copying begins. /// - protected virtual void CopyTo(T[] array!!, int arrayIndex) + protected virtual void CopyTo(T[] array, int arrayIndex) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Length < arrayIndex + Length) { throw new ArgumentException(SR.NumberGreaterThenAvailableSpace, nameof(array)); diff --git a/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs b/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs index 8e7fbef4f2755c..7652e953b5a275 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs @@ -7,8 +7,10 @@ namespace System.Collections { internal static class CollectionHelpers { - internal static void ValidateCopyToArguments(int sourceCount, Array array!!, int index) + internal static void ValidateCopyToArguments(int sourceCount, Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.ObjectModel/src/System/Collections/Generic/DebugView.cs b/src/libraries/System.ObjectModel/src/System/Collections/Generic/DebugView.cs index e9c1554d7925bb..84bca385ff19bc 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/Generic/DebugView.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/Generic/DebugView.cs @@ -9,8 +9,10 @@ internal sealed class CollectionDebugView { private readonly ICollection _collection; - public CollectionDebugView(ICollection collection!!) + public CollectionDebugView(ICollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } diff --git a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs index 266c58fa3e95c4..dc6d2019a722b8 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs @@ -69,8 +69,10 @@ public TItem this[TKey key] } } - public bool Contains(TKey key!!) + public bool Contains(TKey key) { + ArgumentNullException.ThrowIfNull(key); + if (dict != null) { return dict.ContainsKey(key); @@ -87,8 +89,10 @@ public bool Contains(TKey key!!) return false; } - public bool TryGetValue(TKey key!!, [MaybeNullWhen(false)] out TItem item) + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TItem item) { + ArgumentNullException.ThrowIfNull(key); + if (dict != null) { return dict.TryGetValue(key, out item!); @@ -125,8 +129,10 @@ private bool ContainsItem(TItem item) return false; } - public bool Remove(TKey key!!) + public bool Remove(TKey key) { + ArgumentNullException.ThrowIfNull(key); + if (dict != null) { TItem item; diff --git a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs index b822aef67e9446..07fec5bc407a5d 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs @@ -44,7 +44,7 @@ public ObservableCollection() /// same order they are read by the enumerator of the collection. /// /// collection is a null reference - public ObservableCollection(IEnumerable collection!!) : base(new List(collection)) + public ObservableCollection(IEnumerable collection) : base(new List(collection ?? throw new ArgumentNullException(nameof(collection)))) { } @@ -58,7 +58,7 @@ public ObservableCollection(IEnumerable collection!!) : base(new List(coll /// same order they are read by the enumerator of the list. /// /// list is a null reference - public ObservableCollection(List list!!) : base(new List(list)) + public ObservableCollection(List list) : base(new List(list ?? throw new ArgumentNullException(nameof(list)))) { } diff --git a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs index 741741992fa137..453f87b33256c8 100644 --- a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs @@ -32,8 +32,10 @@ public TypeConverterAttribute() /// class, using the specified type as the data converter for the object this attribute /// is bound to. /// - public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type!!) + public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { + ArgumentNullException.ThrowIfNull(type); + ConverterTypeName = type.AssemblyQualifiedName!; } @@ -42,8 +44,10 @@ public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMem /// class, using the specified type name as the data converter for the object this attribute /// is bound to. /// - public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName!!) + public TypeConverterAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName) { + ArgumentNullException.ThrowIfNull(typeName); + ConverterTypeName = typeName; } diff --git a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs index 2a7e742d19cc31..f66901d20cb871 100644 --- a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs @@ -11,16 +11,20 @@ public sealed class TypeDescriptionProviderAttribute : Attribute /// /// Creates a new TypeDescriptionProviderAttribute object. /// - public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string typeName!!) + public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string typeName) { + ArgumentNullException.ThrowIfNull(typeName); + TypeName = typeName; } /// /// Creates a new TypeDescriptionProviderAttribute object. /// - public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type!!) + public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type) { + ArgumentNullException.ThrowIfNull(type); + TypeName = type.AssemblyQualifiedName!; } diff --git a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs index 2bfc2697ceb86f..9df331d4ab2a2a 100644 --- a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs +++ b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs @@ -435,8 +435,10 @@ public unsafe string[] GetValueNames() // The actual api is SetValue(string name, object value) but we only need to set Strings // so this is a cut-down version that supports on that. - internal void SetValue(string name, string value!!) + internal void SetValue(string name, string value) { + ArgumentNullException.ThrowIfNull(value); + if (name != null && name.Length > MaxValueLength) throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs b/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs index 0bb3b555796705..ad9ee1f0847730 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs @@ -16,8 +16,10 @@ public static partial class Activator // Note: CreateInstance returns null for Nullable, e.g. CreateInstance(typeof(int?)) returns null. // - public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicConstructors)] Type type!!, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) + public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { + ArgumentNullException.ThrowIfNull(type); + if (type is System.Reflection.Emit.TypeBuilder) throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder); @@ -86,8 +88,10 @@ public static partial class Activator public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type, bool nonPublic) => CreateInstance(type, nonPublic, wrapExceptions: true); - internal static object? CreateInstance(Type type!!, bool nonPublic, bool wrapExceptions) + internal static object? CreateInstance(Type type, bool nonPublic, bool wrapExceptions) { + ArgumentNullException.ThrowIfNull(type); + if (type.UnderlyingSystemType is not RuntimeType rt) throw new ArgumentException(SR.Arg_MustBeType, nameof(type)); diff --git a/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs b/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs index 1bbae039b0d693..62c165247a0f52 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs @@ -51,9 +51,11 @@ public AggregateException(string? message) /// The exception that is the cause of the current exception. /// The argument /// is null. - public AggregateException(string? message, Exception innerException!!) + public AggregateException(string? message, Exception innerException) : base(message, innerException) { + ArgumentNullException.ThrowIfNull(innerException); + _innerExceptions = new[] { innerException }; } @@ -66,8 +68,8 @@ public AggregateException(string? message, Exception innerException!!) /// is null. /// An element of is /// null. - public AggregateException(IEnumerable innerExceptions!!) : - this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) + public AggregateException(IEnumerable innerExceptions) : + this(SR.AggregateException_ctor_DefaultMessage, innerExceptions ?? throw new ArgumentNullException(nameof(innerExceptions))) { } @@ -80,8 +82,8 @@ public AggregateException(IEnumerable innerExceptions!!) : /// is null. /// An element of is /// null. - public AggregateException(params Exception[] innerExceptions!!) : - this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) + public AggregateException(params Exception[] innerExceptions) : + this(SR.AggregateException_ctor_DefaultMessage, innerExceptions ?? throw new ArgumentNullException(nameof(innerExceptions))) { } @@ -95,8 +97,8 @@ public AggregateException(params Exception[] innerExceptions!!) : /// is null. /// An element of is /// null. - public AggregateException(string? message, IEnumerable innerExceptions!!) - : this(message, new List(innerExceptions).ToArray(), cloneExceptions: false) + public AggregateException(string? message, IEnumerable innerExceptions) + : this(message, new List(innerExceptions ?? throw new ArgumentNullException(nameof(innerExceptions))).ToArray(), cloneExceptions: false) { } @@ -110,8 +112,8 @@ public AggregateException(string? message, IEnumerable innerException /// is null. /// An element of is /// null. - public AggregateException(string? message, params Exception[] innerExceptions!!) : - this(message, innerExceptions, cloneExceptions: true) + public AggregateException(string? message, params Exception[] innerExceptions) : + this(message, innerExceptions ?? throw new ArgumentNullException(nameof(innerExceptions)), cloneExceptions: true) { } @@ -253,8 +255,10 @@ public override Exception GetBaseException() /// cref="AggregateException"/> was not handled. /// The argument is /// null. - public void Handle(Func predicate!!) + public void Handle(Func predicate) { + ArgumentNullException.ThrowIfNull(predicate); + List? unhandledExceptions = null; for (int i = 0; i < _innerExceptions.Length; i++) { diff --git a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs index f7b809143e913d..3a0a12c79341e0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs @@ -30,8 +30,10 @@ public static partial class AppContext // It is the value read from the TargetFrameworkAttribute on the .exe that started the process. Assembly.GetEntryAssembly()?.GetCustomAttribute()?.FrameworkName; - public static object? GetData(string name!!) + public static object? GetData(string name) { + ArgumentNullException.ThrowIfNull(name); + if (s_dataStore == null) return null; @@ -49,8 +51,10 @@ public static partial class AppContext /// The name of the data element /// The value of /// If is - public static void SetData(string name!!, object? data) + public static void SetData(string name, object? data) { + ArgumentNullException.ThrowIfNull(name); + if (s_dataStore == null) { Interlocked.CompareExchange(ref s_dataStore, new Dictionary(), null); diff --git a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs index 27b1a979d49e3f..df8f6c5915e0b4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs @@ -90,8 +90,10 @@ public string ApplyPolicy(string assemblyName) } [Obsolete(Obsoletions.AppDomainCreateUnloadMessage, DiagnosticId = Obsoletions.AppDomainCreateUnloadDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static AppDomain CreateDomain(string friendlyName!!) + public static AppDomain CreateDomain(string friendlyName) { + ArgumentNullException.ThrowIfNull(friendlyName); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains); } @@ -99,8 +101,10 @@ public static AppDomain CreateDomain(string friendlyName!!) public int ExecuteAssembly(string assemblyFile) => ExecuteAssembly(assemblyFile, null); [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public int ExecuteAssembly(string assemblyFile!!, string?[]? args) + public int ExecuteAssembly(string assemblyFile, string?[]? args) { + ArgumentNullException.ThrowIfNull(assemblyFile); + string fullPath = Path.GetFullPath(assemblyFile); Assembly assembly = Assembly.LoadFile(fullPath); return ExecuteAssembly(assembly, args); @@ -157,8 +161,10 @@ public override string ToString() => SR.AppDomain_Name + FriendlyName + Environment.NewLineConst + SR.AppDomain_NoContextPolicies; [Obsolete(Obsoletions.AppDomainCreateUnloadMessage, DiagnosticId = Obsoletions.AppDomainCreateUnloadDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static void Unload(AppDomain domain!!) + public static void Unload(AppDomain domain) { + ArgumentNullException.ThrowIfNull(domain); + throw new CannotUnloadAppDomainException(SR.Arg_PlatformNotSupported); } @@ -255,8 +261,10 @@ public void SetPrincipalPolicy(PrincipalPolicy policy) _principalPolicy = policy; } - public void SetThreadPrincipal(IPrincipal principal!!) + public void SetThreadPrincipal(IPrincipal principal) { + ArgumentNullException.ThrowIfNull(principal); + // Set the principal while checking it has not been set previously. if (Interlocked.CompareExchange(ref _defaultPrincipal, principal, null) is not null) { @@ -265,14 +273,18 @@ public void SetThreadPrincipal(IPrincipal principal!!) } [RequiresUnreferencedCode("Type and its constructor could be removed")] - public ObjectHandle? CreateInstance(string assemblyName!!, string typeName) + public ObjectHandle? CreateInstance(string assemblyName, string typeName) { + ArgumentNullException.ThrowIfNull(assemblyName); + return Activator.CreateInstance(assemblyName, typeName); } [RequiresUnreferencedCode("Type and its constructor could be removed")] - public ObjectHandle? CreateInstance(string assemblyName!!, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) + public ObjectHandle? CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { + ArgumentNullException.ThrowIfNull(assemblyName); + return Activator.CreateInstance(assemblyName, typeName, ignoreCase, @@ -284,8 +296,10 @@ public void SetThreadPrincipal(IPrincipal principal!!) } [RequiresUnreferencedCode("Type and its constructor could be removed")] - public ObjectHandle? CreateInstance(string assemblyName!!, string typeName, object?[]? activationAttributes) + public ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) { + ArgumentNullException.ThrowIfNull(assemblyName); + return Activator.CreateInstance(assemblyName, typeName, activationAttributes); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs index 5cc13227f6e30b..722b1b6cfa9881 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs @@ -208,8 +208,10 @@ internal static bool IsFalseStringIgnoreCase(ReadOnlySpan value) // Determines whether a String represents true or false. // - public static bool Parse(string value!!) + public static bool Parse(string value) { + ArgumentNullException.ThrowIfNull(value); + return Parse(value.AsSpan()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Buffer.cs b/src/libraries/System.Private.CoreLib/src/System/Buffer.cs index c6fc3a5fc063fe..46ec623528a4b1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffer.cs @@ -17,8 +17,11 @@ public static partial class Buffer // respecting types. This calls memmove internally. The count and // offset parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. - public static unsafe void BlockCopy(Array src!!, int srcOffset, Array dst!!, int dstOffset, int count) + public static unsafe void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count) { + ArgumentNullException.ThrowIfNull(src); + ArgumentNullException.ThrowIfNull(dst); + nuint uSrcLen = src.NativeLength; if (src.GetType() != typeof(byte[])) { @@ -56,8 +59,10 @@ public static unsafe void BlockCopy(Array src!!, int srcOffset, Array dst!!, int Memmove(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetArrayDataReference(dst), uDstOffset), ref Unsafe.AddByteOffset(ref MemoryMarshal.GetArrayDataReference(src), uSrcOffset), uCount); } - public static int ByteLength(Array array!!) + public static int ByteLength(Array array) { + ArgumentNullException.ThrowIfNull(array); + // Is it of primitive types? if (!array.GetCorElementTypeOfElementType().IsPrimitiveType()) throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Buffers/ConfigurableArrayPool.cs b/src/libraries/System.Private.CoreLib/src/System/Buffers/ConfigurableArrayPool.cs index af1372f10528fb..2188fc38dbb9f0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffers/ConfigurableArrayPool.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffers/ConfigurableArrayPool.cs @@ -120,8 +120,10 @@ public override T[] Rent(int minimumLength) return buffer; } - public override void Return(T[] array!!, bool clearArray = false) + public override void Return(T[] array, bool clearArray = false) { + ArgumentNullException.ThrowIfNull(array); + if (array.Length == 0) { // Ignore empty arrays. When a zero-length array is rented, we return a singleton diff --git a/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs b/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs index f5578efa0f3209..4c0d3848a6ee84 100644 --- a/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/CodeDom/Compiler/IndentedTextWriter.cs @@ -21,8 +21,10 @@ public class IndentedTextWriter : TextWriter public IndentedTextWriter(TextWriter writer) : this(writer, DefaultTabString) { } - public IndentedTextWriter(TextWriter writer!!, string tabString) : base(CultureInfo.InvariantCulture) + public IndentedTextWriter(TextWriter writer, string tabString) : base(CultureInfo.InvariantCulture) { + ArgumentNullException.ThrowIfNull(writer); + _writer = writer; _tabString = tabString; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs index f0cf8b8655b3db..630e77b74f5ac1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs @@ -60,8 +60,10 @@ public ArrayList(int capacity) // size and capacity of the new list will both be equal to the size of the // given collection. // - public ArrayList(ICollection c!!) + public ArrayList(ICollection c) { + ArgumentNullException.ThrowIfNull(c); + int count = c.Count; if (count == 0) { @@ -149,8 +151,10 @@ public virtual object? this[int index] // However, since these methods are generic, the performance may not be // nearly as good for some operations as they would be on the IList itself. // - public static ArrayList Adapter(IList list!!) + public static ArrayList Adapter(IList list) { + ArgumentNullException.ThrowIfNull(list); + return new IListWrapper(list); } @@ -319,16 +323,20 @@ private void EnsureCapacity(int min) // Returns a list wrapper that is fixed at the current size. Operations // that add or remove items will fail, however, replacing items is allowed. // - public static IList FixedSize(IList list!!) + public static IList FixedSize(IList list) { + ArgumentNullException.ThrowIfNull(list); + return new FixedSizeList(list); } // Returns a list wrapper that is fixed at the current size. Operations // that add or remove items will fail, however, replacing items is allowed. // - public static ArrayList FixedSize(ArrayList list!!) + public static ArrayList FixedSize(ArrayList list) { + ArgumentNullException.ThrowIfNull(list); + return new FixedSizeArrayList(list); } @@ -428,8 +436,10 @@ public virtual void Insert(int index, object? value) // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the ArrayList's size. // - public virtual void InsertRange(int index, ICollection c!!) + public virtual void InsertRange(int index, ICollection c) { + ArgumentNullException.ThrowIfNull(c); + if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); int count = c.Count; @@ -504,15 +514,19 @@ public virtual int LastIndexOf(object? value, int startIndex, int count) // Returns a read-only IList wrapper for the given IList. // - public static IList ReadOnly(IList list!!) + public static IList ReadOnly(IList list) { + ArgumentNullException.ThrowIfNull(list); + return new ReadOnlyList(list); } // Returns a read-only ArrayList wrapper for the given ArrayList. // - public static ArrayList ReadOnly(ArrayList list!!) + public static ArrayList ReadOnly(ArrayList list) { + ArgumentNullException.ThrowIfNull(list); + return new ReadOnlyArrayList(list); } @@ -609,8 +623,10 @@ public virtual void Reverse(int index, int count) // Sets the elements starting at the given index to the elements of the // given collection. // - public virtual void SetRange(int index, ICollection c!!) + public virtual void SetRange(int index, ICollection c) { + ArgumentNullException.ThrowIfNull(c); + int count = c.Count; if (index < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -667,15 +683,19 @@ public virtual void Sort(int index, int count, IComparer? comparer) // Returns a thread-safe wrapper around an IList. // - public static IList Synchronized(IList list!!) + public static IList Synchronized(IList list) { + ArgumentNullException.ThrowIfNull(list); + return new SyncIList(list); } // Returns a thread-safe wrapper around a ArrayList. // - public static ArrayList Synchronized(ArrayList list!!) + public static ArrayList Synchronized(ArrayList list) { + ArgumentNullException.ThrowIfNull(list); + return new SyncArrayList(list); } @@ -697,8 +717,10 @@ public static ArrayList Synchronized(ArrayList list!!) // Internally, this implementation calls Array.Copy. // [RequiresDynamicCode("The code for an array of the specified type might not be available.")] - public virtual Array ToArray(Type type!!) + public virtual Array ToArray(Type type) { + ArgumentNullException.ThrowIfNull(type); + Array array = Array.CreateInstance(type, _size); Array.Copy(_items, array, _size); return array; @@ -832,8 +854,10 @@ public override void CopyTo(Array array, int index) _list.CopyTo(array, index); } - public override void CopyTo(int index, Array array!!, int arrayIndex, int count) + public override void CopyTo(int index, Array array, int arrayIndex, int count) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0 || arrayIndex < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -904,8 +928,10 @@ public override void Insert(int index, object? obj) _version++; } - public override void InsertRange(int index, ICollection c!!) + public override void InsertRange(int index, ICollection c) { + ArgumentNullException.ThrowIfNull(c); + if (index < 0 || index > Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (c.Count > 0) @@ -1014,8 +1040,10 @@ public override void Reverse(int index, int count) _version++; } - public override void SetRange(int index, ICollection c!!) + public override void SetRange(int index, ICollection c) { + ArgumentNullException.ThrowIfNull(c); + if (index < 0 || index > _list.Count - c.Count) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -1069,8 +1097,10 @@ public override void Sort(int index, int count, IComparer? comparer) } [RequiresDynamicCode("The code for an array of the specified type might not be available.")] - public override Array ToArray(Type type!!) + public override Array ToArray(Type type) { + ArgumentNullException.ThrowIfNull(type); + Array array = Array.CreateInstance(type, _list.Count); _list.CopyTo(array, 0); return array; @@ -2207,8 +2237,10 @@ public override int Add(object? value) return _baseSize++; } - public override void AddRange(ICollection c!!) + public override void AddRange(ICollection c) { + ArgumentNullException.ThrowIfNull(c); + InternalUpdateRange(); int count = c.Count; if (count > 0) @@ -2282,8 +2314,10 @@ public override bool Contains(object? item) } } - public override void CopyTo(Array array!!, int index) + public override void CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) @@ -2295,8 +2329,10 @@ public override void CopyTo(Array array!!, int index) _baseList.CopyTo(_baseIndex, array, index, _baseSize); } - public override void CopyTo(int index, Array array!!, int arrayIndex, int count) + public override void CopyTo(int index, Array array, int arrayIndex, int count) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0 || count < 0) @@ -2537,8 +2573,10 @@ public override object? this[int index] } [RequiresDynamicCode("The code for an array of the specified type might not be available.")] - public override Array ToArray(Type type!!) + public override Array ToArray(Type type) { + ArgumentNullException.ThrowIfNull(type); + InternalUpdateRange(); Array array = Array.CreateInstance(type, _baseSize); _baseList.CopyTo(_baseIndex, array, 0, _baseSize); @@ -2646,8 +2684,10 @@ internal sealed class ArrayListDebugView { private readonly ArrayList _arrayList; - public ArrayListDebugView(ArrayList arrayList!!) + public ArrayListDebugView(ArrayList arrayList) { + ArgumentNullException.ThrowIfNull(arrayList); + _arrayList = arrayList; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs index 0403fc238a39d2..d676f813f68637 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs @@ -21,18 +21,24 @@ public sealed class Comparer : IComparer, ISerializable public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture); public static readonly Comparer DefaultInvariant = new Comparer(CultureInfo.InvariantCulture); - public Comparer(CultureInfo culture!!) + public Comparer(CultureInfo culture) { + ArgumentNullException.ThrowIfNull(culture); + _compareInfo = culture.CompareInfo; } - private Comparer(SerializationInfo info!!, StreamingContext context) + private Comparer(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _compareInfo = (CompareInfo)info.GetValue("CompareInfo", typeof(CompareInfo))!; } - public void GetObjectData(SerializationInfo info!!, StreamingContext context) + public void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("CompareInfo", _compareInfo); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs index 27834f8d62a0d7..8ff1c1ee5cfcce 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs @@ -44,8 +44,10 @@ public int Compare(object? a, object? b) throw new ArgumentException(SR.Argument_ImplementIComparable); } - public int GetHashCode(object obj!!) + public int GetHashCode(object obj) { + ArgumentNullException.ThrowIfNull(obj); + return _hcp != null ? _hcp.GetHashCode(obj) : obj.GetHashCode(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs index cbd0024ded8e29..3d9a2b0fdc9105 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/IProducerConsumerCollectionDebugView.cs @@ -18,8 +18,10 @@ internal sealed class IProducerConsumerCollectionDebugView /// Constructs a new debugger view object for the provided collection object. /// /// A collection to browse in the debugger. - public IProducerConsumerCollectionDebugView(IProducerConsumerCollection collection!!) + public IProducerConsumerCollectionDebugView(IProducerConsumerCollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs index 34f1b26c3d2104..1b5d6116587109 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Comparer.cs @@ -13,8 +13,10 @@ public abstract partial class Comparer : IComparer, IComparer { // public static Comparer Default is runtime-specific - public static Comparer Create(Comparison comparison!!) + public static Comparer Create(Comparison comparison) { + ArgumentNullException.ThrowIfNull(comparison); + return new ComparisonComparer(comparison); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs index 524fe11a4d9b32..4e58fc58b20265 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ICollectionDebugView.cs @@ -9,8 +9,10 @@ internal sealed class ICollectionDebugView { private readonly ICollection _collection; - public ICollectionDebugView(ICollection collection!!) + public ICollectionDebugView(ICollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs index 3a564be99c17c9..97e32ad5da7df5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/IDictionaryDebugView.cs @@ -9,8 +9,10 @@ internal sealed class IDictionaryDebugView where K : notnull { private readonly IDictionary _dict; - public IDictionaryDebugView(IDictionary dictionary!!) + public IDictionaryDebugView(IDictionary dictionary) { + ArgumentNullException.ThrowIfNull(dictionary); + _dict = dictionary; } @@ -30,8 +32,10 @@ internal sealed class DictionaryKeyCollectionDebugView { private readonly ICollection _collection; - public DictionaryKeyCollectionDebugView(ICollection collection!!) + public DictionaryKeyCollectionDebugView(ICollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } @@ -51,8 +55,10 @@ internal sealed class DictionaryValueCollectionDebugView { private readonly ICollection _collection; - public DictionaryValueCollectionDebugView(ICollection collection!!) + public DictionaryValueCollectionDebugView(ICollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs index 7743370a587ce0..e9f9f6c307f98d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs @@ -49,8 +49,10 @@ public Queue(int capacity) // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. - public Queue(IEnumerable collection!!) + public Queue(IEnumerable collection) { + ArgumentNullException.ThrowIfNull(collection); + _array = EnumerableHelpers.ToArray(collection, out _size); if (_size != _array.Length) _tail = _size; } @@ -95,8 +97,10 @@ public void Clear() // CopyTo copies a collection into an Array, starting at a particular // index into the array. - public void CopyTo(T[] array!!, int arrayIndex) + public void CopyTo(T[] array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -119,8 +123,10 @@ public void CopyTo(T[] array!!, int arrayIndex) } } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/QueueDebugView.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/QueueDebugView.cs index d0cd1fc26ff65f..8828b4c7adf769 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/QueueDebugView.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/QueueDebugView.cs @@ -9,8 +9,10 @@ internal sealed class QueueDebugView { private readonly Queue _queue; - public QueueDebugView(Queue queue!!) + public QueueDebugView(Queue queue) { + ArgumentNullException.ThrowIfNull(queue); + _queue = queue; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs index 07f51d19e95087..d70a824f6c3bb3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs @@ -342,17 +342,21 @@ public Hashtable(int capacity, float loadFactor, IHashCodeProvider? hcp, ICompar } [Obsolete("This constructor has been deprecated. Use Hashtable(IDictionary, float, IEqualityComparer) instead.")] - public Hashtable(IDictionary d!!, float loadFactor, IHashCodeProvider? hcp, IComparer? comparer) - : this(d.Count, loadFactor, hcp, comparer) + public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider? hcp, IComparer? comparer) + : this(d?.Count ?? 0, loadFactor, hcp, comparer) { + ArgumentNullException.ThrowIfNull(d); + IDictionaryEnumerator e = d.GetEnumerator(); while (e.MoveNext()) Add(e.Key, e.Value); } - public Hashtable(IDictionary d!!, float loadFactor, IEqualityComparer? equalityComparer) - : this(d.Count, loadFactor, equalityComparer) + public Hashtable(IDictionary d, float loadFactor, IEqualityComparer? equalityComparer) + : this(d?.Count ?? 0, loadFactor, equalityComparer) { + ArgumentNullException.ThrowIfNull(d); + IDictionaryEnumerator e = d.GetEnumerator(); while (e.MoveNext()) Add(e.Key, e.Value); @@ -466,8 +470,10 @@ public virtual bool Contains(object key) // Checks if this hashtable contains an entry with the given key. This is // an O(1) operation. // - public virtual bool ContainsKey(object key!!) + public virtual bool ContainsKey(object key) { + ArgumentNullException.ThrowIfNull(key); + // Take a snapshot of buckets, in case another thread resizes table Bucket[] lbuckets = _buckets; uint hashcode = InitHash(key, lbuckets.Length, out uint seed, out uint incr); @@ -559,8 +565,10 @@ private void CopyEntries(Array array, int arrayIndex) // Copies the values in this hash table to an array at // a given index. Note that this only copies values, and not keys. - public virtual void CopyTo(Array array!!, int arrayIndex) + public virtual void CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -820,8 +828,10 @@ protected virtual bool KeyEquals(object? item, object key) // Inserts an entry into this hashtable. This method is called from the Set // and Add methods. If the add parameter is true and the given key already // exists in the hashtable, an exception is thrown. - private void Insert(object key!!, object? nvalue, bool add) + private void Insert(object key, object? nvalue, bool add) { + ArgumentNullException.ThrowIfNull(key); + if (_count >= _loadsize) { expand(); @@ -956,8 +966,10 @@ private void putEntry(Bucket[] newBuckets, object key, object? nvalue, int hashc // key exists in the hashtable, it is removed. An ArgumentException is // thrown if the key is null. // - public virtual void Remove(object key!!) + public virtual void Remove(object key) { + ArgumentNullException.ThrowIfNull(key); + Debug.Assert(!_isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized."); // Assuming only one concurrent writer, write directly into buckets. @@ -1002,13 +1014,17 @@ public virtual void Remove(object key!!) // Returns a thread-safe wrapper for a Hashtable. // - public static Hashtable Synchronized(Hashtable table!!) + public static Hashtable Synchronized(Hashtable table) { + ArgumentNullException.ThrowIfNull(table); + return new SyncHashtable(table); } - public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + // This is imperfect - it only works well if all other writes are // also using our synchronized wrapper. But it's still a good idea. lock (SyncRoot) @@ -1169,8 +1185,10 @@ internal KeyCollection(Hashtable hashtable) _hashtable = hashtable; } - public void CopyTo(Array array!!, int arrayIndex) + public void CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -1203,8 +1221,10 @@ internal ValueCollection(Hashtable hashtable) _hashtable = hashtable; } - public void CopyTo(Array array!!, int arrayIndex) + public void CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -1289,8 +1309,10 @@ public override bool Contains(object key) return _table.Contains(key); } - public override bool ContainsKey(object key!!) + public override bool ContainsKey(object key) { + ArgumentNullException.ThrowIfNull(key); + return _table.ContainsKey(key); } @@ -1481,8 +1503,10 @@ internal sealed class HashtableDebugView { private readonly Hashtable _hashtable; - public HashtableDebugView(Hashtable hashtable!!) + public HashtableDebugView(Hashtable hashtable) { + ArgumentNullException.ThrowIfNull(hashtable); + _hashtable = hashtable; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs index feb3e495bba829..d39a152b069c6c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs @@ -29,10 +29,12 @@ public ListDictionaryInternal() { } - public object? this[object key!!] + public object? this[object key] { get { + ArgumentNullException.ThrowIfNull(key); + DictionaryNode? node = head; while (node != null) @@ -47,6 +49,8 @@ public object? this[object key!!] } set { + ArgumentNullException.ThrowIfNull(key); + version++; DictionaryNode? last = null; DictionaryNode? node; @@ -94,8 +98,10 @@ public object? this[object key!!] public ICollection Values => new NodeKeyValueCollection(this, false); - public void Add(object key!!, object? value) + public void Add(object key, object? value) { + ArgumentNullException.ThrowIfNull(key); + version++; DictionaryNode? last = null; for (DictionaryNode? node = head; node != null; node = node.next) @@ -129,8 +135,10 @@ public void Clear() version++; } - public bool Contains(object key!!) + public bool Contains(object key) { + ArgumentNullException.ThrowIfNull(key); + for (DictionaryNode? node = head; node != null; node = node.next) { if (node.key.Equals(key)) @@ -141,8 +149,10 @@ public bool Contains(object key!!) return false; } - 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); @@ -169,8 +179,10 @@ IEnumerator IEnumerable.GetEnumerator() return new NodeEnumerator(this); } - public void Remove(object key!!) + public void Remove(object key) { + ArgumentNullException.ThrowIfNull(key); + version++; DictionaryNode? last = null; DictionaryNode? node; @@ -293,8 +305,10 @@ public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) this.isKeys = isKeys; } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs index 6b6016d68d7753..ee843c0035732f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/CollectionHelpers.cs @@ -7,8 +7,10 @@ namespace System.Collections.ObjectModel { internal static class CollectionHelpers { - internal static void ValidateCopyToArguments(int sourceCount, Array array!!, int index) + internal static void ValidateCopyToArguments(int sourceCount, Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs index 9e0facdfa34b00..7c45a9fdd56792 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs @@ -20,8 +20,10 @@ public class ReadOnlyDictionary : IDictionary, IDict [NonSerialized] private ValueCollection? _values; - public ReadOnlyDictionary(IDictionary dictionary!!) + public ReadOnlyDictionary(IDictionary dictionary) { + ArgumentNullException.ThrowIfNull(dictionary); + m_dictionary = dictionary; } @@ -105,8 +107,10 @@ IEnumerator IEnumerable.GetEnumerator() return ((IEnumerable)m_dictionary).GetEnumerator(); } - private static bool IsCompatibleKey(object key!!) + private static bool IsCompatibleKey(object key) { + ArgumentNullException.ThrowIfNull(key); + return key is TKey; } @@ -249,8 +253,10 @@ public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCol { private readonly ICollection _collection; - internal KeyCollection(ICollection collection!!) + internal KeyCollection(ICollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } @@ -303,8 +309,10 @@ public sealed class ValueCollection : ICollection, ICollection, IReadOnl { private readonly ICollection _collection; - internal ValueCollection(ICollection collection!!) + internal ValueCollection(ICollection collection) { + ArgumentNullException.ThrowIfNull(collection); + _collection = collection; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Convert.cs b/src/libraries/System.Private.CoreLib/src/System/Convert.cs index 8747eb98e9ab11..326b570edbb043 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Convert.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Convert.cs @@ -226,8 +226,10 @@ public static bool IsDBNull([NotNullWhen(true)] object? value) }; } - internal static object DefaultToType(IConvertible value, Type targetType!!, IFormatProvider? provider) + internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider? provider) { + ArgumentNullException.ThrowIfNull(targetType); + Debug.Assert(value != null, "[Convert.DefaultToType]value!=null"); if (ReferenceEquals(value.GetType(), targetType)) @@ -285,8 +287,10 @@ internal static object DefaultToType(IConvertible value, Type targetType!!, IFor } [return: NotNullIfNotNull("value")] - public static object? ChangeType(object? value, Type conversionType!!, IFormatProvider? provider) + public static object? ChangeType(object? value, Type conversionType, IFormatProvider? provider) { + ArgumentNullException.ThrowIfNull(conversionType); + if (value == null) { if (conversionType.IsValueType) @@ -545,8 +549,10 @@ public static char ToChar(string value) return ToChar(value, null); } - public static char ToChar(string value!!, IFormatProvider? provider) + public static char ToChar(string value, IFormatProvider? provider) { + ArgumentNullException.ThrowIfNull(value); + if (value.Length != 1) throw new FormatException(SR.Format_NeedSingleChar); @@ -2297,13 +2303,17 @@ public static string ToString(long value, int toBase) return ParseNumbers.LongToString(value, toBase, -1, ' ', 0); } - public static string ToBase64String(byte[] inArray!!) + public static string ToBase64String(byte[] inArray) { + ArgumentNullException.ThrowIfNull(inArray); + return ToBase64String(new ReadOnlySpan(inArray), Base64FormattingOptions.None); } - public static string ToBase64String(byte[] inArray!!, Base64FormattingOptions options) + public static string ToBase64String(byte[] inArray, Base64FormattingOptions options) { + ArgumentNullException.ThrowIfNull(inArray); + return ToBase64String(new ReadOnlySpan(inArray), options); } @@ -2312,8 +2322,10 @@ public static string ToBase64String(byte[] inArray, int offset, int length) return ToBase64String(inArray, offset, length, Base64FormattingOptions.None); } - public static string ToBase64String(byte[] inArray!!, int offset, int length, Base64FormattingOptions options) + public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) { + ArgumentNullException.ThrowIfNull(inArray); + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (offset < 0) @@ -2357,8 +2369,11 @@ public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, ch return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None); } - public static unsafe int ToBase64CharArray(byte[] inArray!!, int offsetIn, int length, char[] outArray!!, int offsetOut, Base64FormattingOptions options) + public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) { + ArgumentNullException.ThrowIfNull(inArray); + ArgumentNullException.ThrowIfNull(outArray); + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (offsetIn < 0) @@ -2682,8 +2697,10 @@ private static void CopyToTempBufferWithoutWhiteSpace(ReadOnlySpan chars, /// A position within the input array. /// Number of element to convert. /// The array of bytes represented by the specified Base64 encoding characters. - public static byte[] FromBase64CharArray(char[] inArray!!, int offset, int length) + public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { + ArgumentNullException.ThrowIfNull(inArray); + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); @@ -2857,8 +2874,10 @@ public static byte[] FromHexString(ReadOnlySpan chars) /// The string representation in hex of the elements in . /// is null. /// is too large to be encoded. - public static string ToHexString(byte[] inArray!!) + public static string ToHexString(byte[] inArray) { + ArgumentNullException.ThrowIfNull(inArray); + return ToHexString(new ReadOnlySpan(inArray)); } @@ -2874,8 +2893,10 @@ public static string ToHexString(byte[] inArray!!) /// or is negative. /// plus is greater than the length of . /// is too large to be encoded. - public static string ToHexString(byte[] inArray!!, int offset, int length) + public static string ToHexString(byte[] inArray, int offset, int length) { + ArgumentNullException.ThrowIfNull(inArray); + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual); if (offset < 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index 6623318d2b247e..a0b17f1f90eb73 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -260,8 +260,10 @@ public DateTime(int year, int month, int day, Calendar calendar) /// For applications in which portability of date and time data or a limited degree of time zone awareness is important, /// you can use the corresponding constructor. /// - public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar!!, DateTimeKind kind) + public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) { + ArgumentNullException.ThrowIfNull(calendar); + if ((uint)millisecond >= MillisPerSecond) ThrowMillisecondOutOfRange(); if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind(); @@ -315,8 +317,10 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, // Constructs a DateTime from a given year, month, day, hour, // minute, and second for the specified calendar. // - public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar!!) + public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar) { + ArgumentNullException.ThrowIfNull(calendar); + if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = calendar.ToDateTime(year, month, day, hour, minute, second, 0).UTicks; @@ -486,8 +490,10 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, /// For applications in which portability of date and time data or a limited degree of time zone awareness is important, /// you can use the corresponding constructor. /// - public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar!!) + public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar) { + ArgumentNullException.ThrowIfNull(calendar); + if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = calendar.ToDateTime(year, month, day, hour, minute, second, millisecond).UTicks; @@ -682,7 +688,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, /// For applications in which portability of date and time data or a limited degree of time zone awareness is important, /// you can use the corresponding constructor. /// - public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, Calendar calendar!!) + public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, Calendar calendar) : this(year, month, day, hour, minute, second, millisecond, microsecond, calendar, DateTimeKind.Unspecified) { } @@ -749,7 +755,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, /// For applications in which portability of date and time data or a limited degree of time zone awareness is important, /// you can use the corresponding constructor. /// - public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, Calendar calendar!!, DateTimeKind kind) + public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, Calendar calendar, DateTimeKind kind) : this(year, month, day, hour, minute, second, millisecond, calendar, kind) { if ((uint)microsecond >= MicrosecondsPerMillisecond) diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs index 6c0cce89e445a9..d224435b05e7ad 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs @@ -660,14 +660,18 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("DateTime", _dateTime); // Do not rename (binary serialization) info.AddValue("OffsetMinutes", _offsetMinutes); // Do not rename (binary serialization) } - private DateTimeOffset(SerializationInfo info!!, StreamingContext context) + private DateTimeOffset(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime))!; // Do not rename (binary serialization) _offsetMinutes = (short)info.GetValue("OffsetMinutes", typeof(short))!; // Do not rename (binary serialization) } diff --git a/src/libraries/System.Private.CoreLib/src/System/Decimal.cs b/src/libraries/System.Private.CoreLib/src/System/Decimal.cs index f2613f73ecd748..58e4d79fe3fc9e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Decimal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Decimal.cs @@ -195,15 +195,19 @@ public Decimal(double value) DecCalc.VarDecFromR8(value, out AsMutable(ref this)); } - private Decimal(SerializationInfo info!!, StreamingContext context) + private Decimal(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _flags = info.GetInt32("flags"); _hi32 = (uint)info.GetInt32("hi"); _lo64 = (uint)info.GetInt32("lo") + ((ulong)info.GetInt32("mid") << 32); } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + // Serialize both the old and the new format info.AddValue("flags", _flags); info.AddValue("hi", (int)High); @@ -273,8 +277,8 @@ public static long ToOACurrency(decimal value) // The possible binary representations of a particular value are all // equally valid, and all are numerically equivalent. // - public Decimal(int[] bits!!) : - this((ReadOnlySpan)bits) + public Decimal(int[] bits) : + this((ReadOnlySpan)(bits ?? throw new ArgumentNullException(nameof(bits)))) { } diff --git a/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs b/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs index 32555bb77dd8de..a459ff91d9caad 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs @@ -107,7 +107,6 @@ public sealed override MethodBase BindToMethod( if (candidates[i] == null) continue; - // Validate the parameters. ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); #region Match method by parameter count @@ -432,8 +431,10 @@ public sealed override MethodBase BindToMethod( // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field - public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match!!, object value, CultureInfo? cultureInfo) + public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? cultureInfo) { + ArgumentNullException.ThrowIfNull(match); + int i; // Find the method that match... int CurIdx = 0; @@ -767,8 +768,10 @@ public sealed override void ReorderArgumentArray(ref object?[] args, object stat // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static MethodBase? ExactBinding(MethodBase[] match!!, Type[] types) + public static MethodBase? ExactBinding(MethodBase[] match, Type[] types) { + ArgumentNullException.ThrowIfNull(match); + MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; @@ -807,8 +810,10 @@ public sealed override void ReorderArgumentArray(ref object?[] args, object stat // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match!!, Type? returnType, Type[]? types) + public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types) { + ArgumentNullException.ThrowIfNull(match); + PropertyInfo? bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i = 0; i < match.Length; i++) diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs index bd4852c036593a..36c732acd55838 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Contracts/Contracts.cs @@ -535,8 +535,11 @@ public static bool ForAll(int fromInclusive, int toExclusive, Predicate pre /// . /// [Pure] - public static bool ForAll(IEnumerable collection!!, Predicate predicate!!) + public static bool ForAll(IEnumerable collection, Predicate predicate) { + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(predicate); + foreach (T t in collection) if (!predicate(t)) return false; return true; @@ -578,8 +581,11 @@ public static bool Exists(int fromInclusive, int toExclusive, Predicate pre /// . /// [Pure] - public static bool Exists(IEnumerable collection!!, Predicate predicate!!) + public static bool Exists(IEnumerable collection, Predicate predicate) { + ArgumentNullException.ThrowIfNull(collection); + ArgumentNullException.ThrowIfNull(predicate); + foreach (T t in collection) if (predicate(t)) return true; return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs index bb81ce035c31e7..fc873198b038cc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs @@ -19,8 +19,10 @@ public static partial class Debug { private static volatile DebugProvider s_provider = new DebugProvider(); - public static DebugProvider SetProvider(DebugProvider provider!!) + public static DebugProvider SetProvider(DebugProvider provider) { + ArgumentNullException.ThrowIfNull(provider); + return Interlocked.Exchange(ref s_provider, provider); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs index 982c462535f0c3..fdf5af822bb7dc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs @@ -11,8 +11,10 @@ public sealed class DebuggerTypeProxyAttribute : Attribute private Type? _target; public DebuggerTypeProxyAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { + ArgumentNullException.ThrowIfNull(type); + ProxyTypeName = type.AssemblyQualifiedName!; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs index 1b011101a2f757..fa8f80e50711bb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs @@ -30,30 +30,39 @@ public DebuggerVisualizerAttribute( public DebuggerVisualizerAttribute( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string visualizerTypeName, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizerObjectSource!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizerObjectSource) { + ArgumentNullException.ThrowIfNull(visualizerObjectSource); + VisualizerTypeName = visualizerTypeName; VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer) { + ArgumentNullException.ThrowIfNull(visualizer); + VisualizerTypeName = visualizer.AssemblyQualifiedName!; } public DebuggerVisualizerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer!!, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizerObjectSource!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizerObjectSource) { + ArgumentNullException.ThrowIfNull(visualizer); + ArgumentNullException.ThrowIfNull(visualizerObjectSource); + VisualizerTypeName = visualizer.AssemblyQualifiedName!; VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string? visualizerObjectSourceTypeName) { + ArgumentNullException.ThrowIfNull(visualizer); + VisualizerTypeName = visualizer.AssemblyQualifiedName!; VisualizerObjectSourceTypeName = visualizerObjectSourceTypeName; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs index 81b0e58b12dc57..395076fc5988ee 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs @@ -76,16 +76,20 @@ public StackTrace(int skipFrames, bool fNeedFileInfo) /// /// Constructs a stack trace from the current location. /// - public StackTrace(Exception e!!) + public StackTrace(Exception e) { + ArgumentNullException.ThrowIfNull(e); + InitializeForException(e, METHODS_TO_SKIP, false); } /// /// Constructs a stack trace from the current location. /// - public StackTrace(Exception e!!, bool fNeedFileInfo) + public StackTrace(Exception e, bool fNeedFileInfo) { + ArgumentNullException.ThrowIfNull(e); + InitializeForException(e, METHODS_TO_SKIP, fNeedFileInfo); } @@ -93,8 +97,10 @@ public StackTrace(Exception e!!, bool fNeedFileInfo) /// Constructs a stack trace from the current location, in a caller's /// frame /// - public StackTrace(Exception e!!, int skipFrames) + public StackTrace(Exception e, int skipFrames) { + ArgumentNullException.ThrowIfNull(e); + if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -106,8 +112,10 @@ public StackTrace(Exception e!!, int skipFrames) /// Constructs a stack trace from the current location, in a caller's /// frame /// - public StackTrace(Exception e!!, int skipFrames, bool fNeedFileInfo) + public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { + ArgumentNullException.ThrowIfNull(e); + if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs index 2c605cd8ee48a1..c03c9c5cdd94b5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/DiagnosticCounter.cs @@ -31,10 +31,10 @@ public abstract class DiagnosticCounter : IDisposable /// /// The name. /// The event source. - internal DiagnosticCounter(string Name!!, EventSource EventSource!!) + internal DiagnosticCounter(string Name, EventSource EventSource) { - this.Name = Name; - this.EventSource = EventSource; + this.Name = Name ?? throw new ArgumentNullException(nameof(Name)); + this.EventSource = EventSource ?? throw new ArgumentNullException(nameof(EventSource)); } /// Adds the counter to the set that the EventSource will report on. diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index 2124c8b71a7590..62deac8677b994 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -4175,8 +4175,13 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword /// /// This call never has an effect on other EventListeners. /// - public void EnableEvents(EventSource eventSource!!, EventLevel level, EventKeywords matchAnyKeyword, IDictionary? arguments) + public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary? arguments) { + if (eventSource is null) + { + throw new ArgumentNullException(nameof(eventSource)); + } + eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments); #if FEATURE_PERFTRACING @@ -4191,8 +4196,13 @@ public void EnableEvents(EventSource eventSource!!, EventLevel level, EventKeywo /// /// This call never has an effect on other EventListeners. /// - public void DisableEvents(EventSource eventSource!!) + public void DisableEvents(EventSource eventSource) { + if (eventSource is null) + { + throw new ArgumentNullException(nameof(eventSource)); + } + eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null); #if FEATURE_PERFTRACING diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs index a06de9bb623a1e..21d14e6b0b044f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/IncrementingPollingCounter.cs @@ -35,8 +35,13 @@ public partial class IncrementingPollingCounter : DiagnosticCounter /// The name. /// The event source. /// The delegate to invoke to get the total value for this counter. - public IncrementingPollingCounter(string name, EventSource eventSource, Func totalValueProvider!!) : base(name, eventSource) + public IncrementingPollingCounter(string name, EventSource eventSource, Func totalValueProvider) : base(name, eventSource) { + if (totalValueProvider is null) + { + throw new ArgumentNullException(nameof(totalValueProvider)); + } + _totalValueProvider = totalValueProvider; Publish(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs index e2849498a674a4..a2a4244fd13ad3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/PollingCounter.cs @@ -33,8 +33,13 @@ public partial class PollingCounter : DiagnosticCounter /// The name. /// The event source. /// The delegate to invoke to get the current metric value. - public PollingCounter(string name, EventSource eventSource, Func metricProvider!!) : base(name, eventSource) + public PollingCounter(string name, EventSource eventSource, Func metricProvider) : base(name, eventSource) { + if (metricProvider is null) + { + throw new ArgumentNullException(nameof(metricProvider)); + } + _metricProvider = metricProvider; Publish(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs index fa09bfa8db3260..7ad51bb0caf708 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs @@ -75,8 +75,13 @@ public bool Contains(KeyValuePair entry) return ContainsKey(entry.Key); } - public bool ContainsKey(string key!!) + public bool ContainsKey(string key) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + foreach (string item in m_names) { if (item == key) @@ -118,8 +123,13 @@ public bool Remove(KeyValuePair entry) throw new System.NotSupportedException(); } - public bool TryGetValue(string key!!, [MaybeNullWhen(false)] out object? value) + public bool TryGetValue(string key, [MaybeNullWhen(false)] out object? value) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + int position = 0; foreach (string name in m_names) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs index 8b9fef256dce1c..633cde3195b77e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs @@ -86,12 +86,12 @@ public EventSource( /// /// A collection of key-value strings (must be an even number). public EventSource( - string eventSourceName!!, + string eventSourceName, EventSourceSettings config, params string[]? traits) : this( - GenerateGuidFromName(eventSourceName.ToUpperInvariant()), - eventSourceName!, + GenerateGuidFromName((eventSourceName ?? throw new ArgumentNullException(nameof(eventSourceName))).ToUpperInvariant()), + eventSourceName, config, traits) { } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs index 5716d3b6bbac2f..61a819a0c9bc86 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs @@ -89,10 +89,15 @@ internal TraceLoggingEventTypes( [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("EventSource WriteEvent will serialize the whole object graph. Trimmer will not safely handle this case because properties may be trimmed. This can be suppressed if the object is a primitive type")] #endif internal TraceLoggingEventTypes( - string name!!, + string name, EventTags tags, System.Reflection.ParameterInfo[] paramInfos) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + this.typeInfos = MakeArray(paramInfos); #if FEATURE_PERFTRACING this.paramNames = MakeParamNameArray(paramInfos); @@ -124,9 +129,14 @@ internal TraceLoggingEventTypes( private TraceLoggingEventTypes( EventTags tags, - string defaultName!!, + string defaultName, TraceLoggingTypeInfo[] typeInfos) { + if (defaultName is null) + { + throw new ArgumentNullException(nameof(defaultName)); + } + this.typeInfos = typeInfos; this.name = defaultName; this.tags = tags; @@ -179,8 +189,13 @@ internal NameInfo GetNameInfo(string name, EventTags tags) => #if !ES_BUILD_STANDALONE [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("EventSource WriteEvent will serialize the whole object graph. Trimmer will not safely handle this case because properties may be trimmed. This can be suppressed if the object is a primitive type")] #endif - private static TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] paramInfos!!) + private static TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] paramInfos) { + if (paramInfos is null) + { + throw new ArgumentNullException(nameof(paramInfos)); + } + var recursionCheck = new List(paramInfos.Length); var result = new TraceLoggingTypeInfo[paramInfos.Length]; for (int i = 0; i < paramInfos.Length; ++i) @@ -194,8 +209,13 @@ private static TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[ #if !ES_BUILD_STANDALONE [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("EventSource WriteEvent will serialize the whole object graph. Trimmer will not safely handle this case because properties may be trimmed. This can be suppressed if the object is a primitive type")] #endif - private static TraceLoggingTypeInfo[] MakeArray(Type[] types!!) + private static TraceLoggingTypeInfo[] MakeArray(Type[] types) { + if (types is null) + { + throw new ArgumentNullException(nameof(types)); + } + var recursionCheck = new List(types.Length); var result = new TraceLoggingTypeInfo[types.Length]; for (int i = 0; i < types.Length; i++) @@ -207,8 +227,13 @@ private static TraceLoggingTypeInfo[] MakeArray(Type[] types!!) } private static TraceLoggingTypeInfo[] MakeArray( - TraceLoggingTypeInfo[] typeInfos!!) + TraceLoggingTypeInfo[] typeInfos) { + if (typeInfos is null) + { + throw new ArgumentNullException(nameof(typeInfos)); + } + return (TraceLoggingTypeInfo[])typeInfos.Clone(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs index ad1f46b6b19142..7dc243a62e2d51 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs @@ -27,21 +27,35 @@ internal abstract class TraceLoggingTypeInfo private readonly Type dataType; private readonly Func propertyValueFactory; - internal TraceLoggingTypeInfo(Type dataType!!) + internal TraceLoggingTypeInfo(Type dataType) { + if (dataType is null) + { + throw new ArgumentNullException(nameof(dataType)); + } + this.name = dataType.Name; this.dataType = dataType; this.propertyValueFactory = PropertyValue.GetFactory(dataType); } internal TraceLoggingTypeInfo( - Type dataType!!, - string name!!, + Type dataType, + string name, EventLevel level, EventOpcode opcode, EventKeywords keywords, EventTags tags) { + if (dataType is null) + { + throw new ArgumentNullException(nameof(dataType)); + } + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + Statics.CheckName(name); this.name = name; diff --git a/src/libraries/System.Private.CoreLib/src/System/Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Enum.cs index b319791728a198..f2222e3cb7bc46 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Enum.cs @@ -285,21 +285,30 @@ private static ulong ToUInt64(TEnum value) where TEnum : struct, Enum => public static string? GetName(TEnum value) where TEnum : struct, Enum => GetEnumName((RuntimeType)typeof(TEnum), ToUInt64(value)); - public static string? GetName(Type enumType!!, object value) => - enumType.GetEnumName(value); + public static string? GetName(Type enumType, object value) + { + ArgumentNullException.ThrowIfNull(enumType); + return enumType.GetEnumName(value); + } public static string[] GetNames() where TEnum : struct, Enum => new ReadOnlySpan(InternalGetNames((RuntimeType)typeof(TEnum))).ToArray(); - public static string[] GetNames(Type enumType!!) => - enumType.GetEnumNames(); + public static string[] GetNames(Type enumType) + { + ArgumentNullException.ThrowIfNull(enumType); + return enumType.GetEnumNames(); + } internal static string[] InternalGetNames(RuntimeType enumType) => // Get all of the names GetEnumInfo(enumType, true).Names; - public static Type GetUnderlyingType(Type enumType!!) => - enumType.GetEnumUnderlyingType(); + public static Type GetUnderlyingType(Type enumType) + { + ArgumentNullException.ThrowIfNull(enumType); + return enumType.GetEnumUnderlyingType(); + } #if !CORERT public static TEnum[] GetValues() where TEnum : struct, Enum => @@ -307,12 +316,17 @@ public static TEnum[] GetValues() where TEnum : struct, Enum => #endif [RequiresDynamicCode("It might not be possible to create an array of the enum type at runtime. Use the GetValues overload instead.")] - public static Array GetValues(Type enumType!!) => - enumType.GetEnumValues(); + public static Array GetValues(Type enumType) + { + ArgumentNullException.ThrowIfNull(enumType); + return enumType.GetEnumValues(); + } [Intrinsic] - public bool HasFlag(Enum flag!!) + public bool HasFlag(Enum flag) { + ArgumentNullException.ThrowIfNull(flag); + if (GetType() != flag.GetType() && !GetType().IsEquivalentTo(flag.GetType())) throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), GetType())); @@ -393,8 +407,10 @@ private static int FindDefinedIndex(ulong[] ulValues, ulong ulValue) SpanHelpers.BinarySearch(ref start, ulValuesLength, ulValue); } - public static bool IsDefined(Type enumType!!, object value) + public static bool IsDefined(Type enumType, object value) { + ArgumentNullException.ThrowIfNull(enumType); + return enumType.IsEnumDefined(value); } @@ -515,7 +531,7 @@ private static bool TryParse(Type enumType, string? value, bool ignoreCase, bool { if (throwOnFailure) { - throw new ArgumentNullException(nameof(value)); + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } result = null; return false; @@ -994,8 +1010,10 @@ private static bool TryParseByName(RuntimeType enumType, ReadOnlySpan valu [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool StartsNumber(char c) => char.IsInRange(c, '0', '9') || c == '-' || c == '+'; - public static object ToObject(Type enumType, object value!!) + public static object ToObject(Type enumType, object value) { + ArgumentNullException.ThrowIfNull(value); + // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); @@ -1015,8 +1033,11 @@ public static object ToObject(Type enumType, object value!!) }; } - public static string Format(Type enumType, object value!!, [StringSyntax(StringSyntaxAttribute.EnumFormat)] string format!!) + public static string Format(Type enumType, object value, [StringSyntax(StringSyntaxAttribute.EnumFormat)] string format) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(format); + RuntimeType rtType = ValidateRuntimeType(enumType); // If the value is an Enum then we need to extract the underlying value from it @@ -1461,8 +1482,10 @@ private static object ToObject(Type enumType, bool value) => #endregion - private static RuntimeType ValidateRuntimeType(Type enumType!!) + private static RuntimeType ValidateRuntimeType(Type enumType) { + ArgumentNullException.ThrowIfNull(enumType); + if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (enumType is not RuntimeType rtType) diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.cs index b3b011ac005dbf..84eeeb5032f646 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.cs @@ -21,8 +21,10 @@ public static partial class Environment // Unconditionally return false since .NET Core does not support object finalization during shutdown. public static bool HasShutdownStarted => false; - public static string? GetEnvironmentVariable(string variable!!) + public static string? GetEnvironmentVariable(string variable) { + ArgumentNullException.ThrowIfNull(variable); + return GetEnvironmentVariableCore(variable); } @@ -78,8 +80,10 @@ public static string CurrentDirectory } } - public static string ExpandEnvironmentVariables(string name!!) + public static string ExpandEnvironmentVariables(string name) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) return name; diff --git a/src/libraries/System.Private.CoreLib/src/System/Exception.cs b/src/libraries/System.Private.CoreLib/src/System/Exception.cs index bfc03ebbbe4aa3..f8271606e92b49 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Exception.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Exception.cs @@ -38,8 +38,10 @@ public Exception(string? message, Exception? innerException) _innerException = innerException; } - protected Exception(SerializationInfo info!!, StreamingContext context) + protected Exception(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _message = info.GetString("Message"); // Do not rename (binary serialization) _data = (IDictionary?)(info.GetValueNoThrow("Data", typeof(IDictionary))); // Do not rename (binary serialization) _innerException = (Exception?)(info.GetValue("InnerException", typeof(Exception))); // Do not rename (binary serialization) @@ -93,8 +95,10 @@ public virtual string? Source set => _source = value; } - public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _source ??= Source; // Set the Source information correctly before serialization info.AddValue("ClassName", GetClassName(), typeof(string)); // Do not rename (binary serialization) diff --git a/src/libraries/System.Private.CoreLib/src/System/FormattableString.cs b/src/libraries/System.Private.CoreLib/src/System/FormattableString.cs index 90d69cba5aaf65..60b16ccf09d968 100644 --- a/src/libraries/System.Private.CoreLib/src/System/FormattableString.cs +++ b/src/libraries/System.Private.CoreLib/src/System/FormattableString.cs @@ -63,8 +63,11 @@ string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) = /// Invariant($"{{ lat = {latitude}; lon = {longitude} }}") /// /// - public static string Invariant(FormattableString formattable!!) => - formattable.ToString(Globalization.CultureInfo.InvariantCulture); + public static string Invariant(FormattableString formattable) + { + ArgumentNullException.ThrowIfNull(formattable); + return formattable.ToString(Globalization.CultureInfo.InvariantCulture); + } /// /// Format the given object in the current culture. This static method may be @@ -79,8 +82,11 @@ public static string Invariant(FormattableString formattable!!) => /// CurrentCulture($"{{ lat = {latitude}; lon = {longitude} }}") /// /// - public static string CurrentCulture(FormattableString formattable!!) => - formattable.ToString(Globalization.CultureInfo.CurrentCulture); + public static string CurrentCulture(FormattableString formattable) + { + ArgumentNullException.ThrowIfNull(formattable); + return formattable.ToString(Globalization.CultureInfo.CurrentCulture); + } public override string ToString() => ToString(Globalization.CultureInfo.CurrentCulture); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs index 63e148d0c7c2b3..b572d526b04e87 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs @@ -82,8 +82,10 @@ public virtual object Clone() return o; } - public static Calendar ReadOnly(Calendar calendar!!) + public static Calendar ReadOnly(Calendar calendar) { + ArgumentNullException.ThrowIfNull(calendar); + if (calendar.IsReadOnly) { return calendar; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs index 98af70570c0fd5..573b8c80d96ccd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Icu.cs @@ -628,8 +628,10 @@ private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan source, ReadOnlySpa } } - private unsafe SortKey IcuCreateSortKey(string source!!, CompareOptions options) + private unsafe SortKey IcuCreateSortKey(string source, CompareOptions options) { + ArgumentNullException.ThrowIfNull(source); + Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs index 0de506a38d3b4f..739f461cc8628b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs @@ -9,8 +9,10 @@ namespace System.Globalization { public partial class CompareInfo { - private SortKey InvariantCreateSortKey(string source!!, CompareOptions options) + private SortKey InvariantCreateSortKey(string source, CompareOptions options) { + ArgumentNullException.ThrowIfNull(source); + if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs index 379a98b97fd2c6..152b55a3e2f701 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Nls.cs @@ -366,8 +366,10 @@ private unsafe bool NlsEndsWith(ReadOnlySpan source, ReadOnlySpan su private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; - private unsafe SortKey NlsCreateSortKey(string source!!, CompareOptions options) + private unsafe SortKey NlsCreateSortKey(string source, CompareOptions options) { + ArgumentNullException.ThrowIfNull(source); + Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs index 64f012d6b180b7..3f0f6f5613bad8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs @@ -60,8 +60,10 @@ internal CompareInfo(CultureInfo culture) /// assembly for the specified culture. /// Warning: The assembly versioning mechanism is dead! /// - public static CompareInfo GetCompareInfo(int culture, Assembly assembly!!) + public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { + ArgumentNullException.ThrowIfNull(assembly); + // Parameter checking. if (assembly != typeof(object).Module.Assembly) { @@ -76,8 +78,11 @@ public static CompareInfo GetCompareInfo(int culture, Assembly assembly!!) /// assembly for the specified culture. /// The purpose of this method is to provide version for CompareInfo tables. /// - public static CompareInfo GetCompareInfo(string name!!, Assembly assembly!!) + public static CompareInfo GetCompareInfo(string name, Assembly assembly) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(assembly); + if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib, nameof(assembly)); @@ -103,8 +108,10 @@ public static CompareInfo GetCompareInfo(int culture) /// /// Get the CompareInfo for the specified culture. /// - public static CompareInfo GetCompareInfo(string name!!) + public static CompareInfo GetCompareInfo(string name) { + ArgumentNullException.ThrowIfNull(name); + return CultureInfo.GetCultureInfo(name).CompareInfo; } @@ -113,8 +120,10 @@ public static bool IsSortable(char ch) return IsSortable(new ReadOnlySpan(in ch)); } - public static bool IsSortable(string text!!) + public static bool IsSortable(string text) { + ArgumentNullException.ThrowIfNull(text); + return IsSortable(text.AsSpan()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs index 48ac59fc2fe608..3b73e45d77ef82 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -164,8 +164,10 @@ public CultureInfo(string name) : this(name, true) { } - public CultureInfo(string name!!, bool useUserOverride) + public CultureInfo(string name, bool useUserOverride) { + ArgumentNullException.ThrowIfNull(name); + // Get our data providing record CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); @@ -238,8 +240,10 @@ public CultureInfo(int culture, bool useUserOverride) /// name we create for it has to include both names, and the logic for this is in /// the GetCultureInfo override *only*. /// - internal CultureInfo(string cultureName, string textAndCompareCultureName!!) + internal CultureInfo(string cultureName, string textAndCompareCultureName) { + ArgumentNullException.ThrowIfNull(textAndCompareCultureName); + CultureData? cultureData = CultureData.GetCultureData(cultureName, false) ?? throw new CultureNotFoundException(nameof(cultureName), cultureName, GetCultureNotSupportedExceptionMessage()); @@ -949,8 +953,10 @@ public virtual object Clone() return ci; } - public static CultureInfo ReadOnly(CultureInfo ci!!) + public static CultureInfo ReadOnly(CultureInfo ci) { + ArgumentNullException.ThrowIfNull(ci); + if (ci.IsReadOnly) { return ci; @@ -1056,8 +1062,10 @@ public static CultureInfo GetCultureInfo(int culture) /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). (Named version) /// - public static CultureInfo GetCultureInfo(string name!!) + public static CultureInfo GetCultureInfo(string name) { + ArgumentNullException.ThrowIfNull(name); + name = CultureData.AnsiToLower(name); Dictionary nameTable = CachedCulturesByName; CultureInfo? result; @@ -1090,8 +1098,11 @@ public static CultureInfo GetCultureInfo(string name!!) /// Gets a cached copy of the specified culture from an internal /// hashtable (or creates it if not found). /// - public static CultureInfo GetCultureInfo(string name!!, string altName!!) + public static CultureInfo GetCultureInfo(string name, string altName) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(altName); + name = CultureData.AnsiToLower(name); altName = CultureData.AnsiToLower(altName); string nameAndAltName = name + "\xfffd" + altName; @@ -1126,8 +1137,10 @@ public static CultureInfo GetCultureInfo(string name!!, string altName!!) return result; } - public static CultureInfo GetCultureInfo(string name!!, bool predefinedOnly) + public static CultureInfo GetCultureInfo(string name, bool predefinedOnly) { + ArgumentNullException.ThrowIfNull(name); + if (predefinedOnly && !GlobalizationMode.Invariant) { if (GlobalizationMode.UseNls ? !CultureData.NlsIsEnsurePredefinedLocaleName(name): !CultureData.IcuIsEnsurePredefinedLocaleName(name)) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs index 77f18189633022..65859a6d32a325 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs @@ -476,8 +476,10 @@ public Calendar Calendar /// /// Get the era value by parsing the name of the era. /// - public int GetEra(string eraName!!) + public int GetEra(string eraName) { + ArgumentNullException.ThrowIfNull(eraName); + // The Era Name and Abbreviated Era Name // for Taiwan Calendar on non-Taiwan SKU returns empty string (which // would be matched below) but we don't want the empty string to give @@ -1583,8 +1585,10 @@ private string[] UnclonedLongTimePatterns } } - public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi!!) + public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) { + ArgumentNullException.ThrowIfNull(dtfi); + if (dtfi.IsReadOnly) { return dtfi; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs index 919f0cf7cc486c..d7d4ff32bcd25e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs @@ -5,8 +5,10 @@ namespace System.Globalization { public static class GlobalizationExtensions { - public static StringComparer GetStringComparer(this CompareInfo compareInfo!!, CompareOptions options) + public static StringComparer GetStringComparer(this CompareInfo compareInfo, CompareOptions options) { + ArgumentNullException.ThrowIfNull(compareInfo); + if (options == CompareOptions.Ordinal) { return StringComparer.Ordinal; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs index 03af442f3c1b2e..c832591b094878 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs @@ -56,13 +56,17 @@ public bool UseStd3AsciiRules public string GetAscii(string unicode) => GetAscii(unicode, 0); - public string GetAscii(string unicode!!, int index) + public string GetAscii(string unicode, int index) { + ArgumentNullException.ThrowIfNull(unicode); + return GetAscii(unicode, index, unicode.Length - index); } - public string GetAscii(string unicode!!, int index, int count) + public string GetAscii(string unicode, int index, int count) { + ArgumentNullException.ThrowIfNull(unicode); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > unicode.Length) @@ -99,13 +103,17 @@ public string GetAscii(string unicode!!, int index, int count) public string GetUnicode(string ascii) => GetUnicode(ascii, 0); - public string GetUnicode(string ascii!!, int index) + public string GetUnicode(string ascii, int index) { + ArgumentNullException.ThrowIfNull(ascii); + return GetUnicode(ascii, index, ascii.Length - index); } - public string GetUnicode(string ascii!!, int index, int count) + public string GetUnicode(string ascii, int index, int count) { + ArgumentNullException.ThrowIfNull(ascii); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > ascii.Length) diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs index fa8b8ab2680b97..3d2c60fd01550b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs @@ -80,8 +80,10 @@ public NumberFormatInfo() { } - private static void VerifyNativeDigits(string[] nativeDig!!, string propertyName) + private static void VerifyNativeDigits(string[] nativeDig, string propertyName) { + ArgumentNullException.ThrowIfNull(nativeDig); + if (nativeDig.Length != 10) { throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName); @@ -644,8 +646,10 @@ public DigitShapes DigitSubstitution return formatType == typeof(NumberFormatInfo) ? this : null; } - public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi!!) + public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { + ArgumentNullException.ThrowIfNull(nfi); + if (nfi.IsReadOnly) { return nfi; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs index 01b1edd10cbf65..091f3a8f6561c8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs @@ -23,8 +23,10 @@ public class RegionInfo // The RegionInfo for our current region internal static volatile RegionInfo? s_currentRegionInfo; - public RegionInfo(string name!!) + public RegionInfo(string name) { + ArgumentNullException.ThrowIfNull(name); + // The InvariantCulture has no matching region if (name.Length == 0) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs index 231a4594608b8a..a8c54f662d8428 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs @@ -43,8 +43,11 @@ internal SortKey(CompareInfo compareInfo, string str, CompareOptions options, by /// equal, a number less than 0 if sortkey1 is less than sortkey2, /// and a number greater than 0 if sortkey1 is greater than sortkey2. /// - public static int Compare(SortKey sortkey1!!, SortKey sortkey2!!) + public static int Compare(SortKey sortkey1, SortKey sortkey2) { + ArgumentNullException.ThrowIfNull(sortkey1); + ArgumentNullException.ThrowIfNull(sortkey2); + byte[] key1Data = sortkey1._keyData; byte[] key2Data = sortkey2._keyData; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs index 05890c1c572d9a..3ce857988a217f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -89,8 +89,10 @@ public object Clone() /// Create a cloned readonly instance or return the input one if it is /// readonly. /// - public static TextInfo ReadOnly(TextInfo textInfo!!) + public static TextInfo ReadOnly(TextInfo textInfo) { + ArgumentNullException.ThrowIfNull(textInfo); + if (textInfo.IsReadOnly) { return textInfo; @@ -163,8 +165,10 @@ internal static char ToLowerInvariant(char c) return Invariant.ChangeCase(c, toUpper: false); } - public string ToLower(string str!!) + public string ToLower(string str) { + ArgumentNullException.ThrowIfNull(str); + if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToLower(str); @@ -572,8 +576,10 @@ internal static char ToUpperInvariant(char c) return Invariant.ChangeCase(c, toUpper: true); } - public string ToUpper(string str!!) + public string ToUpper(string str) { + ArgumentNullException.ThrowIfNull(str); + if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToUpper(str); @@ -645,8 +651,10 @@ public override string ToString() /// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example /// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English. /// - public unsafe string ToTitleCase(string str!!) + public unsafe string ToTitleCase(string str) { + ArgumentNullException.ThrowIfNull(str); + if (str.Length == 0) { return str; diff --git a/src/libraries/System.Private.CoreLib/src/System/Guid.cs b/src/libraries/System.Private.CoreLib/src/System/Guid.cs index 3984e6c63104ec..ba112f440a1967 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Guid.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Guid.cs @@ -40,8 +40,8 @@ public readonly partial struct Guid private readonly byte _k; // Do not rename (binary serialization) // Creates a new guid from an array of bytes. - public Guid(byte[] b!!) : - this(new ReadOnlySpan(b)) + public Guid(byte[] b) : + this(new ReadOnlySpan(b ?? throw new ArgumentNullException(nameof(b)))) { } @@ -90,8 +90,10 @@ public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, } // Creates a new GUID initialized to the value represented by the arguments. - public Guid(int a, short b, short c, byte[] d!!) + public Guid(int a, short b, short c, byte[] d) { + ArgumentNullException.ThrowIfNull(d); + if (d.Length != 8) { throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); @@ -208,8 +210,10 @@ public void ReverseAbcEndianness() // The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where // d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4, // then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223" - public Guid(string g!!) + public Guid(string g) { + ArgumentNullException.ThrowIfNull(g); + var result = new GuidResult(GuidParseThrowStyle.All); bool success = TryParseGuid(g, ref result); Debug.Assert(success, "GuidParseThrowStyle.All means throw on all failures"); @@ -217,8 +221,11 @@ public Guid(string g!!) this = result.ToGuid(); } - public static Guid Parse(string input!!) => - Parse((ReadOnlySpan)input); + public static Guid Parse(string input) + { + ArgumentNullException.ThrowIfNull(input); + return Parse((ReadOnlySpan)input); + } public static Guid Parse(ReadOnlySpan input) { @@ -255,8 +262,13 @@ public static bool TryParse(ReadOnlySpan input, out Guid result) } } - public static Guid ParseExact(string input!!, [StringSyntax(StringSyntaxAttribute.GuidFormat)] string format!!) => - ParseExact((ReadOnlySpan)input, (ReadOnlySpan)format); + public static Guid ParseExact(string input, [StringSyntax(StringSyntaxAttribute.GuidFormat)] string format) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(format); + + return ParseExact((ReadOnlySpan)input, (ReadOnlySpan)format); + } public static Guid ParseExact(ReadOnlySpan input, [StringSyntax(StringSyntaxAttribute.GuidFormat)] ReadOnlySpan format) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs index a9e94ca5bce630..3d157427060b54 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs @@ -45,8 +45,11 @@ public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, fal { } - public BinaryReader(Stream input!!, Encoding encoding!!, bool leaveOpen) + public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(encoding); + if (!input.CanRead) { throw new ArgumentException(SR.Argument_StreamNotReadable); @@ -309,8 +312,10 @@ public virtual string ReadString() return StringBuilderCache.GetStringAndRelease(sb); } - public virtual int Read(char[] buffer!!, int index, int count) + public virtual int Read(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -437,8 +442,10 @@ public virtual char[] ReadChars(int count) return chars; } - public virtual int Read(byte[] buffer!!, int index, int count) + public virtual int Read(byte[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs index 5ed90b7582d675..12053a582cb832 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs @@ -42,8 +42,11 @@ public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, f { } - public BinaryWriter(Stream output!!, Encoding encoding!!, bool leaveOpen) + public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(encoding); + if (!output.CanWrite) throw new ArgumentException(SR.Argument_StreamNotWritable); @@ -150,8 +153,10 @@ public virtual long Seek(int offset, SeekOrigin origin) // This default implementation calls the Write(Object, int, int) // method to write the byte array. // - public virtual void Write(byte[] buffer!!) + public virtual void Write(byte[] buffer) { + ArgumentNullException.ThrowIfNull(buffer); + OutStream.Write(buffer, 0, buffer.Length); } @@ -209,8 +214,10 @@ public virtual void Write(char ch) // This default implementation calls the Write(Object, int, int) // method to write the character array. // - public virtual void Write(char[] chars!!) + public virtual void Write(char[] chars) { + ArgumentNullException.ThrowIfNull(chars); + WriteCharsCommonWithoutLengthPrefix(chars, useThisWriteOverride: false); } @@ -219,8 +226,10 @@ public virtual void Write(char[] chars!!) // This default implementation calls the Write(Object, int, int) // method to write the character array. // - public virtual void Write(char[] chars!!, int index, int count) + public virtual void Write(char[] chars, int index, int count) { + ArgumentNullException.ThrowIfNull(chars); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -336,8 +345,10 @@ public virtual void Write(Half value) // an encoded unsigned integer with variable length, and then writes that many characters // to the stream. // - public virtual void Write(string value!!) + public virtual void Write(string value) { + ArgumentNullException.ThrowIfNull(value); + // Common: UTF-8, small string, avoid 2-pass calculation // Less common: UTF-8, large string, avoid 2-pass calculation // Uncommon: excessively large string or not UTF-8 diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Directory.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Directory.cs index c23e466380a5fc..8e85f3a74e2cc1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Directory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Directory.cs @@ -152,11 +152,14 @@ public static string[] GetFileSystemEntries(string path, string searchPattern, E => new List(InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions)).ToArray(); internal static IEnumerable InternalEnumeratePaths( - string path!!, - string searchPattern!!, + string path, + string searchPattern, SearchTarget searchTarget, EnumerationOptions options) { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(searchPattern); + FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType); return searchTarget switch @@ -201,8 +204,10 @@ public static IEnumerable EnumerateFileSystemEntries(string path, string public static IEnumerable EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions) => InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions); - public static string GetDirectoryRoot(string path!!) + public static string GetDirectoryRoot(string path) { + ArgumentNullException.ThrowIfNull(path); + string fullPath = Path.GetFullPath(path); string root = Path.GetPathRoot(fullPath)!; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/DirectoryInfo.cs b/src/libraries/System.Private.CoreLib/src/System/IO/DirectoryInfo.cs index f412243f097a2a..2417f93f556b30 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/DirectoryInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/DirectoryInfo.cs @@ -25,8 +25,10 @@ internal DirectoryInfo(string originalPath, string? fullPath = null, string? fil Init(originalPath, fullPath, fileName, isNormalized); } - private void Init(string originalPath!!, string? fullPath = null, string? fileName = null, bool isNormalized = false) + private void Init(string originalPath, string? fullPath = null, string? fileName = null, bool isNormalized = false) { + ArgumentNullException.ThrowIfNull(originalPath); + OriginalPath = originalPath; fullPath = fullPath ?? originalPath; @@ -55,8 +57,10 @@ public DirectoryInfo? Parent } } - public DirectoryInfo CreateSubdirectory(string path!!) + public DirectoryInfo CreateSubdirectory(string path) { + ArgumentNullException.ThrowIfNull(path); + if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); if (Path.IsPathRooted(path)) @@ -163,10 +167,12 @@ public IEnumerable EnumerateFileSystemInfos(string searchPattern private IEnumerable InternalEnumerateInfos( string path, - string searchPattern!!, + string searchPattern, SearchTarget searchTarget, EnumerationOptions options) { + ArgumentNullException.ThrowIfNull(searchPattern); + Debug.Assert(path != null); _isNormalized &= FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerable.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerable.cs index f15399452c5958..ac11ca66c4c5a4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerable.cs @@ -23,8 +23,11 @@ public FileSystemEnumerable(string directory, FindTransform transform, Enumerati { } - internal FileSystemEnumerable(string directory!!, FindTransform transform!!, EnumerationOptions? options, bool isNormalized) + internal FileSystemEnumerable(string directory, FindTransform transform, EnumerationOptions? options, bool isNormalized) { + ArgumentNullException.ThrowIfNull(directory); + ArgumentNullException.ThrowIfNull(transform); + _directory = directory; _transform = transform; _options = options ?? EnumerationOptions.Default; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.cs index 536cb8c41748fd..7d774d7e51a8c3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.cs @@ -28,8 +28,10 @@ public FileSystemEnumerator(string directory, EnumerationOptions? options = null /// The directory to search in. /// Whether the directory path is already normalized or not. /// Enumeration options to use. - internal FileSystemEnumerator(string directory!!, bool isNormalized, EnumerationOptions? options = null) + internal FileSystemEnumerator(string directory, bool isNormalized, EnumerationOptions? options = null) { + ArgumentNullException.ThrowIfNull(directory); + _originalRootDirectory = directory; string path = isNormalized ? directory : Path.GetFullPath(directory); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs index c2906595d49981..fc459f19bfefe3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs @@ -26,13 +26,13 @@ public static class File internal const int DefaultBufferSize = 4096; - public static StreamReader OpenText(string path!!) + public static StreamReader OpenText(string path) => new StreamReader(path); - public static StreamWriter CreateText(string path!!) + public static StreamWriter CreateText(string path) => new StreamWriter(path, append: false); - public static StreamWriter AppendText(string path!!) + public static StreamWriter AppendText(string path) => new StreamWriter(path, append: true); /// @@ -78,8 +78,11 @@ public static FileStream Create(string path, int bufferSize, FileOptions options // // On Windows, Delete will fail for a file that is open for normal I/O // or a file that is memory mapped. - public static void Delete(string path!!) - => FileSystem.DeleteFile(Path.GetFullPath(path)); + public static void Delete(string path) + { + ArgumentNullException.ThrowIfNull(path); + FileSystem.DeleteFile(Path.GetFullPath(path)); + } // Tests whether a file exists. The result is true if the file // given by the specified path exists; otherwise, the result is @@ -375,8 +378,11 @@ public static void AppendAllLines(string path, IEnumerable contents, Enc public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName) => Replace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false); - public static void Replace(string sourceFileName!!, string destinationFileName!!, string? destinationBackupFileName, bool ignoreMetadataErrors) + public static void Replace(string sourceFileName, string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors) { + ArgumentNullException.ThrowIfNull(sourceFileName); + ArgumentNullException.ThrowIfNull(destinationFileName); + FileSystem.ReplaceFile( Path.GetFullPath(sourceFileName), Path.GetFullPath(destinationFileName), @@ -412,12 +418,18 @@ public static void Move(string sourceFileName, string destFileName, bool overwri } [SupportedOSPlatform("windows")] - public static void Encrypt(string path!!) - => FileSystem.Encrypt(path); + public static void Encrypt(string path) + { + ArgumentNullException.ThrowIfNull(path); + FileSystem.Encrypt(path); + } [SupportedOSPlatform("windows")] - public static void Decrypt(string path!!) - => FileSystem.Decrypt(path); + public static void Decrypt(string path) + { + ArgumentNullException.ThrowIfNull(path); + FileSystem.Decrypt(path); + } // If we use the path-taking constructors we will not have FileOptions.Asynchronous set and // we will have asynchronous file access faked by the thread pool. We want the real thing. diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileInfo.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileInfo.cs index cbc5ec0eca7e28..efa2a139b133bf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileInfo.cs @@ -18,8 +18,10 @@ public FileInfo(string fileName) { } - internal FileInfo(string originalPath!!, string? fullPath = null, string? fileName = null, bool isNormalized = false) + internal FileInfo(string originalPath, string? fullPath = null, string? fileName = null, bool isNormalized = false) { + ArgumentNullException.ThrowIfNull(originalPath); + // Want to throw the original argument name OriginalPath = originalPath; @@ -163,8 +165,10 @@ public void MoveTo(string destFileName, bool overwrite) public FileInfo Replace(string destinationFileName, string? destinationBackupFileName) => Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors: false); - public FileInfo Replace(string destinationFileName!!, string? destinationBackupFileName, bool ignoreMetadataErrors) + public FileInfo Replace(string destinationFileName, string? destinationBackupFileName, bool ignoreMetadataErrors) { + ArgumentNullException.ThrowIfNull(destinationFileName); + FileSystem.ReplaceFile( FullPath, Path.GetFullPath(destinationFileName), diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileStream.cs index 95dfe7c703197f..5f4ebb82c6b377 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStream.cs @@ -532,8 +532,10 @@ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, Asy return _strategy.BeginRead(buffer, offset, count, callback, state); } - public override int EndRead(IAsyncResult asyncResult!!) + public override int EndRead(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + return _strategy.EndRead(asyncResult); } @@ -553,8 +555,10 @@ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, As return _strategy.BeginWrite(buffer, offset, count, callback, state); } - public override void EndWrite(IAsyncResult asyncResult!!) + public override void EndWrite(IAsyncResult asyncResult) { + ArgumentNullException.ThrowIfNull(asyncResult); + _strategy.EndWrite(asyncResult); } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs index c4e9ce3489e066..2ca3983a20e991 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs @@ -59,8 +59,10 @@ public MemoryStream(byte[] buffer) { } - public MemoryStream(byte[] buffer!!, bool writable) + public MemoryStream(byte[] buffer, bool writable) { + ArgumentNullException.ThrowIfNull(buffer); + _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; @@ -77,8 +79,10 @@ public MemoryStream(byte[] buffer, int index, int count, bool writable) { } - public MemoryStream(byte[] buffer!!, int index, int count, bool writable, bool publiclyVisible) + public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -756,8 +760,10 @@ public override void WriteByte(byte value) } // Writes this MemoryStream to another stream. - public virtual void WriteTo(Stream stream!!) + public virtual void WriteTo(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + EnsureNotClosed(); stream.Write(_buffer, _origin, _length - _origin); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs index a3c2faa7487497..899dc764f3e3d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs @@ -33,8 +33,11 @@ public static string GetFullPath(string path) return GetFullPathInternal(path); } - public static string GetFullPath(string path!!, string basePath!!) + public static string GetFullPath(string path, string basePath) { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(basePath); + if (!IsPathFullyQualified(basePath)) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs index 1b4f0119202024..690f2782389a24 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs @@ -38,8 +38,10 @@ private static bool ExistsCore(string fullPath, out bool isDirectory) } // Expands the given path to a fully qualified path. - public static string GetFullPath(string path!!) + public static string GetFullPath(string path) { + ArgumentNullException.ThrowIfNull(path); + // If the path would normalize to string empty, we'll consider it empty if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); @@ -53,8 +55,11 @@ public static string GetFullPath(string path!!) return GetFullPathInternal(path); } - public static string GetFullPath(string path!!, string basePath!!) + public static string GetFullPath(string path, string basePath) { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(basePath); + if (!IsPathFullyQualified(basePath)) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs index 2afe0d303d1b47..14481a82bf9fb0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs @@ -303,8 +303,10 @@ public static unsafe string GetRandomFileName() /// /// Thrown if is null. /// - public static bool IsPathFullyQualified(string path!!) + public static bool IsPathFullyQualified(string path) { + ArgumentNullException.ThrowIfNull(path); + return IsPathFullyQualified(path.AsSpan()); } @@ -341,23 +343,37 @@ public static bool HasExtension(ReadOnlySpan path) return false; } - public static string Combine(string path1!!, string path2!!) + public static string Combine(string path1, string path2) { + ArgumentNullException.ThrowIfNull(path1); + ArgumentNullException.ThrowIfNull(path2); + return CombineInternal(path1, path2); } - public static string Combine(string path1!!, string path2!!, string path3!!) + public static string Combine(string path1, string path2, string path3) { + ArgumentNullException.ThrowIfNull(path1); + ArgumentNullException.ThrowIfNull(path2); + ArgumentNullException.ThrowIfNull(path3); + return CombineInternal(path1, path2, path3); } - public static string Combine(string path1!!, string path2!!, string path3!!, string path4!!) + public static string Combine(string path1, string path2, string path3, string path4) { + ArgumentNullException.ThrowIfNull(path1); + ArgumentNullException.ThrowIfNull(path2); + ArgumentNullException.ThrowIfNull(path3); + ArgumentNullException.ThrowIfNull(path4); + return CombineInternal(path1, path2, path3, path4); } - public static string Combine(params string[] paths!!) + public static string Combine(params string[] paths) { + ArgumentNullException.ThrowIfNull(paths); + int maxSize = 0; int firstComponent = 0; @@ -476,8 +492,10 @@ public static string Join(string? path1, string? path2, string? path3, string? p return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan(), path4.AsSpan()); } - public static string Join(params string?[] paths!!) + public static string Join(params string?[] paths) { + ArgumentNullException.ThrowIfNull(paths); + if (paths.Length == 0) { return string.Empty; @@ -842,8 +860,11 @@ public static string GetRelativePath(string relativeTo, string path) return GetRelativePath(relativeTo, path, PathInternal.StringComparison); } - private static string GetRelativePath(string relativeTo!!, string path!!, StringComparison comparisonType) + private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) { + ArgumentNullException.ThrowIfNull(relativeTo); + ArgumentNullException.ThrowIfNull(path); + if (PathInternal.IsEffectivelyEmpty(relativeTo.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(relativeTo)); if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs index 53f5920b967039..828cc6f63f2cad 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs @@ -719,8 +719,11 @@ public virtual void Write(ReadOnlySpan buffer) public virtual void WriteByte(byte value) => Write(new byte[1] { value }, 0, 1); - public static Stream Synchronized(Stream stream!!) => - stream as SyncStream ?? new SyncStream(stream); + public static Stream Synchronized(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream); + return stream as SyncStream ?? new SyncStream(stream); + } [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } @@ -761,8 +764,10 @@ protected static void ValidateBufferArguments(byte[] buffer, int offset, int cou /// was not a positive value. /// does not support writing. /// does not support writing or reading. - protected static void ValidateCopyToArguments(Stream destination!!, int bufferSize) + protected static void ValidateCopyToArguments(Stream destination, int bufferSize) { + ArgumentNullException.ThrowIfNull(destination); + if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum); @@ -863,7 +868,7 @@ private sealed class SyncStream : Stream, IDisposable { private readonly Stream _stream; - internal SyncStream(Stream stream!!) => _stream = stream; + internal SyncStream(Stream stream) => _stream = stream; public override bool CanRead => _stream.CanRead; public override bool CanWrite => _stream.CanWrite; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs index 2d3db53b3d77b5..2b88da71b2898c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs @@ -344,8 +344,10 @@ public override int Read() return result; } - public override int Read(char[] buffer!!, int index, int count) + public override int Read(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -423,8 +425,10 @@ public override string ReadToEnd() return sb.ToString(); } - public override int ReadBlock(char[] buffer!!, int index, int count) + public override int ReadBlock(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -998,8 +1002,10 @@ private async Task ReadToEndAsyncInternal(CancellationToken cancellation return sb.ToString(); } - public override Task ReadAsync(char[] buffer!!, int index, int count) + public override Task ReadAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -1217,8 +1223,10 @@ internal override async ValueTask ReadAsyncInternal(Memory buffer, Ca return charsRead; } - public override Task ReadBlockAsync(char[] buffer!!, int index, int count) + public override Task ReadBlockAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs index 22d18a04042cff..1d74f6e1defa11 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs @@ -367,8 +367,10 @@ public override void Write(char[]? buffer) } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites - public override void Write(char[] buffer!!, int index, int count) + public override void Write(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -693,8 +695,10 @@ public override Task WriteAsync(string? value) } } - public override Task WriteAsync(char[] buffer!!, int index, int count) + public override Task WriteAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -849,8 +853,10 @@ public override Task WriteLineAsync(string? value) return task; } - public override Task WriteLineAsync(char[] buffer!!, int index, int count) + public override Task WriteLineAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs index 8ea5f1083f2331..ecb756ef736d0c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs @@ -83,8 +83,10 @@ public override int Read() // array starting at position index. Returns the actual number of // characters read, or zero if the end of the string is reached. // - public override int Read(char[] buffer!!, int index, int count) + public override int Read(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -288,8 +290,10 @@ public override Task ReadToEndAsync(CancellationToken cancellationToken) ? Task.FromCanceled(cancellationToken) : Task.FromResult(ReadToEnd()); - public override Task ReadBlockAsync(char[] buffer!!, int index, int count) + public override Task ReadBlockAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -306,8 +310,10 @@ public override ValueTask ReadBlockAsync(Memory buffer, CancellationT cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled(cancellationToken) : new ValueTask(ReadBlock(buffer.Span)); - public override Task ReadAsync(char[] buffer!!, int index, int count) + public override Task ReadAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs index 1213573f6bb5fb..eba845fa37d9c4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs @@ -35,8 +35,10 @@ public StringWriter(StringBuilder sb) : this(sb, CultureInfo.CurrentCulture) { } - public StringWriter(StringBuilder sb!!, IFormatProvider? formatProvider) : base(formatProvider) + public StringWriter(StringBuilder sb, IFormatProvider? formatProvider) : base(formatProvider) { + ArgumentNullException.ThrowIfNull(sb); + _sb = sb; _isOpen = true; } @@ -93,8 +95,10 @@ public override void Write(char value) // StringWriter from the buffer character array starting at position // index. // - public override void Write(char[] buffer!!, int index, int count) + public override void Write(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs index 299103cf093eb0..793bb1c4371a55 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs @@ -67,8 +67,10 @@ public virtual int Read() // buffer character array starting at position // index. Returns the actual number of characters read. // - public virtual int Read(char[] buffer!!, int index, int count) + public virtual int Read(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -261,8 +263,10 @@ public virtual async Task ReadToEndAsync(CancellationToken cancellationT return sb.ToString(); } - public virtual Task ReadAsync(char[] buffer!!, int index, int count) + public virtual Task ReadAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -291,8 +295,10 @@ internal virtual ValueTask ReadAsyncInternal(Memory buffer, Cancellat return t.Item1.Read(t.Item2.Span); }, new TupleSlim>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); - public virtual Task ReadBlockAsync(char[] buffer!!, int index, int count) + public virtual Task ReadBlockAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -327,8 +333,10 @@ internal async ValueTask ReadBlockAsyncInternal(Memory buffer, Cancel } #endregion - public static TextReader Synchronized(TextReader reader!!) + public static TextReader Synchronized(TextReader reader) { + ArgumentNullException.ThrowIfNull(reader); + return reader is SyncTextReader ? reader : new SyncTextReader(reader); } @@ -389,8 +397,10 @@ public override Task ReadToEndAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] - public override Task ReadBlockAsync(char[] buffer!!, int index, int count) + public override Task ReadBlockAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) @@ -400,8 +410,10 @@ public override Task ReadBlockAsync(char[] buffer!!, int index, int count) } [MethodImpl(MethodImplOptions.Synchronized)] - public override Task ReadAsync(char[] buffer!!, int index, int count) + public override Task ReadAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs index 567ffb49db7be1..131a0197110743 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs @@ -144,8 +144,10 @@ public virtual void Write(char[]? buffer) // write count characters of data into this TextWriter from the // buffer character array starting at position index. // - public virtual void Write(char[] buffer!!, int index, int count) + public virtual void Write(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -698,8 +700,10 @@ public override void Write(char value) } } - public static TextWriter Synchronized(TextWriter writer!!) + public static TextWriter Synchronized(TextWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + return writer is SyncTextWriter ? writer : new SyncTextWriter(writer); } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs index a77d0f53a8ebb9..f895be77711962 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -45,8 +45,10 @@ public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity, Fi Initialize(buffer, offset, capacity, access); } - protected void Initialize(SafeBuffer buffer!!, long offset, long capacity, FileAccess access) + protected void Initialize(SafeBuffer buffer, long offset, long capacity, FileAccess access) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -325,8 +327,10 @@ public void Read(long position, out T structure) where T : struct // Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'. // Note: this method is not safe, since it overwrites the contents of structures, it can // be used to modify the private members of a struct. - public int ReadArray(long position, T[] array!!, int offset, int count) where T : struct + public int ReadArray(long position, T[] array, int offset, int count) where T : struct { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -561,8 +565,10 @@ public void Write(long position, ref T structure) where T : struct } // Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory. - public void WriteArray(long position, T[] array!!, int offset, int count) where T : struct + public void WriteArray(long position, T[] array, int offset, int count) where T : struct { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs index 11a2727310919e..ca701762b0bc0e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs @@ -82,8 +82,10 @@ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAc /// /// /// - protected void Initialize(SafeBuffer buffer!!, long offset, long length, FileAccess access) + protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -157,8 +159,10 @@ public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, F /// Subclasses must call this method (or the other overload) to properly initialize all instance fields. /// [CLSCompliant(false)] - protected unsafe void Initialize(byte* pointer!!, long length, long capacity, FileAccess access) + protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { + ArgumentNullException.ThrowIfNull(pointer); + if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (length > capacity) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs index 43790c1e2a49c1..d3a8bab317eecf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -119,8 +119,10 @@ public override void WriteByte(byte value) } // Writes this MemoryStream to another stream. - public override unsafe void WriteTo(Stream stream!!) + public override unsafe void WriteTo(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + byte[] buffer = ToArray(); stream.Write(buffer, 0, buffer.Length); @@ -135,8 +137,10 @@ public override void SetLength(long value) } - public override Task CopyToAsync(Stream destination!!, int bufferSize, CancellationToken cancellationToken) + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(destination); + if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs b/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs index bc97638d3568f2..eaa465a5a604f4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs @@ -76,8 +76,10 @@ private unsafe IntPtr(SerializationInfo info, StreamingContext context) _value = (void*)l; } - unsafe void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("value", ToInt64()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs index d3e93f2fd78499..4ff4af7bc4a634 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs @@ -62,8 +62,10 @@ public static class WebUtility return sb.ToString(); } - public static void HtmlEncode(string? value, TextWriter output!!) + public static void HtmlEncode(string? value, TextWriter output) { + ArgumentNullException.ThrowIfNull(output); + if (string.IsNullOrEmpty(value)) { output.Write(value); @@ -201,8 +203,10 @@ private static void HtmlEncode(ReadOnlySpan input, ref ValueStringBuilder return sb.ToString(); } - public static void HtmlDecode(string? value, TextWriter output!!) + public static void HtmlDecode(string? value, TextWriter output) { + ArgumentNullException.ThrowIfNull(output); + if (string.IsNullOrEmpty(value)) { output.Write(value); diff --git a/src/libraries/System.Private.CoreLib/src/System/Nullable.cs b/src/libraries/System.Private.CoreLib/src/System/Nullable.cs index d23f336cc6a84f..6d951c9cd9bb02 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Nullable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Nullable.cs @@ -97,8 +97,10 @@ public static bool Equals(Nullable n1, Nullable n2) where T : struct // If the type provided is not a Nullable Type, return null. // Otherwise, returns the underlying type of the Nullable type - public static Type? GetUnderlyingType(Type nullableType!!) + public static Type? GetUnderlyingType(Type nullableType) { + ArgumentNullException.ThrowIfNull(nullableType); + #if CORERT // This is necessary to handle types without reflection metadata if (nullableType.TryGetEEType(out EETypePtr nullableEEType)) diff --git a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs index 5f1d83dd01ee32..0913c4dafdc9be 100644 --- a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs +++ b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs @@ -87,8 +87,10 @@ public string VersionString /// Indicates whether the current application is running on the specified platform. /// /// Case-insensitive platform name. Examples: Browser, Linux, FreeBSD, Android, iOS, macOS, tvOS, watchOS, Windows. - public static bool IsOSPlatform(string platform!!) + public static bool IsOSPlatform(string platform) { + ArgumentNullException.ThrowIfNull(platform); + #if TARGET_BROWSER return platform.Equals("BROWSER", StringComparison.OrdinalIgnoreCase); #elif TARGET_WINDOWS diff --git a/src/libraries/System.Private.CoreLib/src/System/Progress.cs b/src/libraries/System.Private.CoreLib/src/System/Progress.cs index 462ca510be8fa5..237c8841adbd82 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Progress.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Progress.cs @@ -45,8 +45,10 @@ public Progress() /// could be invoked concurrently with itself. /// /// The is null (Nothing in Visual Basic). - public Progress(Action handler!!) : this() + public Progress(Action handler) : this() { + ArgumentNullException.ThrowIfNull(handler); + _handler = handler; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs index 3879a325857afb..82acb845f1e045 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs @@ -203,7 +203,15 @@ public override string ToString() public static string CreateQualifiedName(string? assemblyName, string? typeName) => typeName + ", " + assemblyName; - public static Assembly? GetAssembly(Type type!!) => type.Module?.Assembly; + public static Assembly? GetAssembly(Type type) + { + if (type is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.type); + } + + return type.Module?.Assembly; + } // internal test hook private static bool s_forceNullEntryPoint; @@ -223,8 +231,10 @@ public override string ToString() // an emitted assembly. The assembly is loaded into a fully isolated ALC with resolution fully deferred to the AssemblyLoadContext.Default. // The second parameter is the raw bytes representing the symbol store that matches the assembly. [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public static Assembly Load(byte[] rawAssembly!!, byte[]? rawSymbolStore) + public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) { + ArgumentNullException.ThrowIfNull(rawAssembly); + if (rawAssembly.Length == 0) throw new BadImageFormatException(SR.BadImageFormat_BadILFormat); @@ -236,8 +246,10 @@ public static Assembly Load(byte[] rawAssembly!!, byte[]? rawSymbolStore) } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public static Assembly LoadFile(string path!!) + public static Assembly LoadFile(string path) { + ArgumentNullException.ThrowIfNull(path); + if (PathInternal.IsPartiallyQualified(path)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, path), nameof(path)); @@ -321,8 +333,10 @@ public static Assembly LoadFile(string path!!) } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public static Assembly LoadFrom(string assemblyFile!!) + public static Assembly LoadFrom(string assemblyFile) { + ArgumentNullException.ThrowIfNull(assemblyFile); + string fullPath = Path.GetFullPath(assemblyFile); if (!s_loadFromHandlerSet) diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyFileVersionAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyFileVersionAttribute.cs index 32265d443bcda9..0b0a1948a5e180 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyFileVersionAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyFileVersionAttribute.cs @@ -6,8 +6,10 @@ namespace System.Reflection [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyFileVersionAttribute : Attribute { - public AssemblyFileVersionAttribute(string version!!) + public AssemblyFileVersionAttribute(string version) { + ArgumentNullException.ThrowIfNull(version); + Version = version; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs index 39d9968e0d84dc..496887dca12248 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs @@ -10,23 +10,31 @@ namespace System.Reflection public class CustomAttributeData { #region Public Static Members - public static IList GetCustomAttributes(MemberInfo target!!) + public static IList GetCustomAttributes(MemberInfo target) { + ArgumentNullException.ThrowIfNull(target); + return target.GetCustomAttributesData(); } - public static IList GetCustomAttributes(Module target!!) + public static IList GetCustomAttributes(Module target) { + ArgumentNullException.ThrowIfNull(target); + return target.GetCustomAttributesData(); } - public static IList GetCustomAttributes(Assembly target!!) + public static IList GetCustomAttributes(Assembly target) { + ArgumentNullException.ThrowIfNull(target); + return target.GetCustomAttributesData(); } - public static IList GetCustomAttributes(ParameterInfo target!!) + public static IList GetCustomAttributes(ParameterInfo target) { + ArgumentNullException.ThrowIfNull(target); + return target.GetCustomAttributesData(); } #endregion diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs index 1ec818145a76af..92551b1b2ba8d5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs @@ -13,8 +13,10 @@ namespace System.Reflection private readonly MemberInfo _memberInfo; private readonly CustomAttributeTypedArgument _value; - public CustomAttributeNamedArgument(MemberInfo memberInfo!!, object? value) + public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value) { + ArgumentNullException.ThrowIfNull(memberInfo); + Type type = memberInfo switch { FieldInfo field => field.FieldType, @@ -26,8 +28,10 @@ public CustomAttributeNamedArgument(MemberInfo memberInfo!!, object? value) _value = new CustomAttributeTypedArgument(type, value); } - public CustomAttributeNamedArgument(MemberInfo memberInfo!!, CustomAttributeTypedArgument typedArgument) + public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) { + ArgumentNullException.ThrowIfNull(memberInfo); + _memberInfo = memberInfo; _value = typedArgument; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs index 0ed140d4f821ea..e91941fc4df3a9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs @@ -15,14 +15,18 @@ namespace System.Reflection private readonly object? _value; private readonly Type _argumentType; - public CustomAttributeTypedArgument(Type argumentType!!, object? value) + public CustomAttributeTypedArgument(Type argumentType, object? value) { + ArgumentNullException.ThrowIfNull(argumentType); + _value = CanonicalizeValue(value); _argumentType = argumentType; } - public CustomAttributeTypedArgument(object value!!) + public CustomAttributeTypedArgument(object value) { + ArgumentNullException.ThrowIfNull(value); + _value = CanonicalizeValue(value); _argumentType = value.GetType(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs index 6ce244b43309b6..9f4a9e8b569237 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs @@ -5,8 +5,10 @@ namespace System.Reflection { public static class IntrospectionExtensions { - public static TypeInfo GetTypeInfo(this Type type!!) + public static TypeInfo GetTypeInfo(this Type type) { + ArgumentNullException.ThrowIfNull(type); + if (type is IReflectableType reflectableType) return reflectableType.GetTypeInfo(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs index cbf100581b0037..4db2512f9861ec 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs @@ -35,16 +35,21 @@ protected Module() { } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Methods might be removed")] - public MethodInfo? GetMethod(string name!!) + public MethodInfo? GetMethod(string name) { + ArgumentNullException.ThrowIfNull(name); + return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, null, null); } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo? GetMethod(string name, Type[] types) => GetMethod(name, Module.DefaultLookup, null, CallingConventions.Any, types, null); [RequiresUnreferencedCode("Methods might be removed")] - public MethodInfo? GetMethod(string name!!, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types!!, ParameterModifier[]? modifiers) + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(types); + for (int i = 0; i < types.Length; i++) { ArgumentNullException.ThrowIfNull(types[i], nameof(types)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs index 6e71fcf4e8b607..43d2b65fc218e6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -63,8 +63,10 @@ private enum NotAnnotatedStatus /// The parameter which nullability info gets populated /// If the parameterInfo parameter is null /// - public NullabilityInfo Create(ParameterInfo parameterInfo!!) + public NullabilityInfo Create(ParameterInfo parameterInfo) { + ArgumentNullException.ThrowIfNull(parameterInfo); + EnsureIsSupported(); IList attributes = parameterInfo.GetCustomAttributesData(); @@ -174,8 +176,10 @@ private static void CheckNullabilityAttributes(NullabilityInfo nullability, ILis /// The parameter which nullability info gets populated /// If the propertyInfo parameter is null /// - public NullabilityInfo Create(PropertyInfo propertyInfo!!) + public NullabilityInfo Create(PropertyInfo propertyInfo) { + ArgumentNullException.ThrowIfNull(propertyInfo); + EnsureIsSupported(); MethodInfo? getter = propertyInfo.GetGetMethod(true); @@ -225,8 +229,10 @@ private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method) /// The parameter which nullability info gets populated /// If the eventInfo parameter is null /// - public NullabilityInfo Create(EventInfo eventInfo!!) + public NullabilityInfo Create(EventInfo eventInfo) { + ArgumentNullException.ThrowIfNull(eventInfo); + EnsureIsSupported(); return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType!, CreateParser(eventInfo.GetCustomAttributesData())); @@ -240,8 +246,10 @@ public NullabilityInfo Create(EventInfo eventInfo!!) /// The parameter which nullability info gets populated /// If the fieldInfo parameter is null /// - public NullabilityInfo Create(FieldInfo fieldInfo!!) + public NullabilityInfo Create(FieldInfo fieldInfo) { + ArgumentNullException.ThrowIfNull(fieldInfo); + EnsureIsSupported(); IList attributes = fieldInfo.GetCustomAttributesData(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs index 5154011e6b9717..319c7070d10b50 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs @@ -26,13 +26,21 @@ protected ParameterInfo() { } public virtual object? RawDefaultValue => throw NotImplemented.ByDesign; public virtual bool HasDefaultValue => throw NotImplemented.ByDesign; - public virtual bool IsDefined(Type attributeType!!, bool inherit) => false; + public virtual bool IsDefined(Type attributeType, bool inherit) + { + ArgumentNullException.ThrowIfNull(attributeType); + return false; + } public virtual IEnumerable CustomAttributes => GetCustomAttributesData(); public virtual IList GetCustomAttributesData() { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(bool inherit) => Array.Empty(); - public virtual object[] GetCustomAttributes(Type attributeType!!, bool inherit) => Array.Empty(); + public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) + { + ArgumentNullException.ThrowIfNull(attributeType); + return Array.Empty(); + } public virtual Type[] GetOptionalCustomModifiers() => Type.EmptyTypes; public virtual Type[] GetRequiredCustomModifiers() => Type.EmptyTypes; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs index 38e82b50ab1372..2d311272cb8b12 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs @@ -20,8 +20,10 @@ private Pointer(void* ptr, RuntimeType ptrType) _ptrType = ptrType; } - public static object Box(void* ptr, Type type!!) + public static object Box(void* ptr, Type type) { + ArgumentNullException.ThrowIfNull(type); + if (!type.IsPointer) throw new ArgumentException(SR.Arg_MustBePointer, nameof(ptr)); if (type is not RuntimeType rtType) diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs index 3b7cd22a8adedb..34d6380c538386 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs @@ -11,8 +11,10 @@ protected ReflectionContext() { } public abstract TypeInfo MapType(TypeInfo type); - public virtual TypeInfo GetTypeForObject(object value!!) + public virtual TypeInfo GetTypeForObject(object value) { + ArgumentNullException.ThrowIfNull(value); + return MapType(value.GetType().GetTypeInfo()); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs index c5f4d7b1345c7f..046979aac68ef5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs @@ -49,8 +49,10 @@ private static InvocationFlags ComputeAndUpdateInvocationFlags(ConstructorInfo c return invocationFlags; } - internal static void CheckCanCreateInstance(Type declaringType!!, bool isVarArg) + internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) { + ArgumentNullException.ThrowIfNull(declaringType); + // ctor is declared on interface class if (declaringType.IsInterface) throw new MemberAccessException( diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs index f0950b7e45307b..6c561d50da01d3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs @@ -12,72 +12,94 @@ public static partial class RuntimeReflectionExtensions public static IEnumerable GetRuntimeFields( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] - this Type type!!) + this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetFields(Everything); } public static IEnumerable GetRuntimeMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - this Type type!!) + this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethods(Everything); } public static IEnumerable GetRuntimeProperties( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - this Type type!!) + this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperties(Everything); } public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] - this Type type!!) + this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetEvents(Everything); } public static FieldInfo? GetRuntimeField( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - this Type type!!, string name) + this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetField(name); } public static MethodInfo? GetRuntimeMethod( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - this Type type!!, string name, Type[] parameters) + this Type type, string name, Type[] parameters) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethod(name, parameters); } public static PropertyInfo? GetRuntimeProperty( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] - this Type type!!, string name) + this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperty(name); } public static EventInfo? GetRuntimeEvent( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] - this Type type!!, string name) + this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetEvent(name); } - public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method!!) + public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method) { + ArgumentNullException.ThrowIfNull(method); + return method.GetBaseDefinition(); } - public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo!!, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) + public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { + ArgumentNullException.ThrowIfNull(typeInfo); + return typeInfo.GetInterfaceMap(interfaceType); } - public static MethodInfo GetMethodInfo(this Delegate del!!) + public static MethodInfo GetMethodInfo(this Delegate del) { + ArgumentNullException.ThrowIfNull(del); + return del.Method; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs index 4b1a91d891be5b..45d5f50c528fc3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs @@ -9,8 +9,11 @@ internal sealed class SignatureConstructedGenericType : SignatureType { // The exception-visible name "typeArguments" is chosen to match the parameter name to Type.MakeGenericType() since that's the // intended user of this constructor. - internal SignatureConstructedGenericType(Type genericTypeDefinition!!, Type[] typeArguments!!) + internal SignatureConstructedGenericType(Type genericTypeDefinition, Type[] typeArguments) { + ArgumentNullException.ThrowIfNull(genericTypeDefinition); + ArgumentNullException.ThrowIfNull(typeArguments); + typeArguments = (Type[])(typeArguments.Clone()); for (int i = 0; i < typeArguments.Length; i++) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs index 4551aaf0ce67f6..ce3e75cde26061 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs @@ -27,8 +27,10 @@ protected TypeDelegator() { } // NOTE: delegatingType is marked as DynamicallyAccessedMemberTypes.All, but analysis tools special case // calls to this constructor and propagate the existing dataflow metadata from delegatingType to this // TypeDelegator. The only purpose of the annotation here is to avoid dataflow warnings _within_ this type. - public TypeDelegator([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type delegatingType!!) + public TypeDelegator([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type delegatingType) { + ArgumentNullException.ThrowIfNull(delegatingType); + typeImpl = delegatingType; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs index bec4cdc06db093..ceed4e4133523e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs @@ -9,14 +9,18 @@ namespace System.Resources [EditorBrowsable(EditorBrowsableState.Never)] public sealed class NeutralResourcesLanguageAttribute : Attribute { - public NeutralResourcesLanguageAttribute(string cultureName!!) + public NeutralResourcesLanguageAttribute(string cultureName) { + ArgumentNullException.ThrowIfNull(cultureName); + CultureName = cultureName; Location = UltimateResourceFallbackLocation.MainAssembly; } - public NeutralResourcesLanguageAttribute(string cultureName!!, UltimateResourceFallbackLocation location) + public NeutralResourcesLanguageAttribute(string cultureName, UltimateResourceFallbackLocation location) { + ArgumentNullException.ThrowIfNull(cultureName); + if (!Enum.IsDefined(typeof(UltimateResourceFallbackLocation), location)) throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, location)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index 2c7ca1dddebdbc..7a9b6a1188db74 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -168,10 +168,13 @@ protected ResourceManager() // // Note: System.Windows.Forms uses this method at design time. // - private ResourceManager(string baseName!!, string resourceDir!!, + private ResourceManager(string baseName, string resourceDir, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type? userResourceSet) { + ArgumentNullException.ThrowIfNull(baseName); + ArgumentNullException.ThrowIfNull(resourceDir); + BaseNameField = baseName; _moduleDir = resourceDir; @@ -183,8 +186,11 @@ private ResourceManager(string baseName!!, string resourceDir!!, _resourceGroveler = new FileBasedResourceGroveler(mediator); } - public ResourceManager(string baseName!!, Assembly assembly!!) + public ResourceManager(string baseName, Assembly assembly) { + ArgumentNullException.ThrowIfNull(baseName); + ArgumentNullException.ThrowIfNull(assembly); + if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -194,10 +200,13 @@ public ResourceManager(string baseName!!, Assembly assembly!!) CommonAssemblyInit(); } - public ResourceManager(string baseName!!, Assembly assembly!!, + public ResourceManager(string baseName, Assembly assembly, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type? usingResourceSet) { + ArgumentNullException.ThrowIfNull(baseName); + ArgumentNullException.ThrowIfNull(assembly); + if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -211,8 +220,10 @@ public ResourceManager(string baseName!!, Assembly assembly!!, CommonAssemblyInit(); } - public ResourceManager(Type resourceSource!!) + public ResourceManager(Type resourceSource) { + ArgumentNullException.ThrowIfNull(resourceSource); + if (resourceSource is not RuntimeType) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -377,8 +388,10 @@ protected virtual string GetResourceFileName(CultureInfo culture) // if it hasn't yet been loaded and if parent CultureInfos should be // loaded as well for resource inheritance. // - public virtual ResourceSet? GetResourceSet(CultureInfo culture!!, bool createIfNotExists, bool tryParents) + public virtual ResourceSet? GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { + ArgumentNullException.ThrowIfNull(culture); + Dictionary? localResourceSets = _resourceSets; ResourceSet? rs; if (localResourceSets != null) @@ -509,8 +522,10 @@ private static void AddResourceSet(Dictionary localResource } } - protected static Version? GetSatelliteContractVersion(Assembly a!!) + protected static Version? GetSatelliteContractVersion(Assembly a) { + ArgumentNullException.ThrowIfNull(a); + string? v = a.GetCustomAttribute()?.Version; if (v == null) { @@ -575,8 +590,10 @@ internal static bool IsDefaultType(string asmTypeName, // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual string? GetString(string name!!, CultureInfo? culture) + public virtual string? GetString(string name, CultureInfo? culture) { + ArgumentNullException.ThrowIfNull(name); + culture ??= CultureInfo.CurrentUICulture; ResourceSet? last = GetFirstResourceSet(culture); @@ -639,8 +656,10 @@ internal static bool IsDefaultType(string asmTypeName, return GetObject(name, culture, true); } - private object? GetObject(string name!!, CultureInfo? culture, bool wrapUnmanagedMemStream) + private object? GetObject(string name, CultureInfo? culture, bool wrapUnmanagedMemStream) { + ArgumentNullException.ThrowIfNull(name); + if (null == culture) { culture = CultureInfo.CurrentUICulture; @@ -717,8 +736,10 @@ internal sealed class ResourceManagerMediator { private readonly ResourceManager _rm; - internal ResourceManagerMediator(ResourceManager rm!!) + internal ResourceManagerMediator(ResourceManager rm) { + ArgumentNullException.ThrowIfNull(rm); + _rm = rm; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs index 5ccdb9f2b6f406..bde195d12e420d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.Core.cs @@ -131,8 +131,10 @@ private static bool ValidateReaderType(string readerType) return ResourceManager.IsDefaultType(readerType, ResourceManager.ResReaderTypeName); } - public void GetResourceData(string resourceName!!, out string resourceType, out byte[] resourceData) + public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) { + ArgumentNullException.ThrowIfNull(resourceName); + if (_resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs index 31fb6574b06445..912236e7cddb73 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs @@ -110,13 +110,20 @@ public sealed partial class public #if RESOURCES_EXTENSIONS - DeserializingResourceReader(Stream stream!!) + DeserializingResourceReader(Stream stream) #else - ResourceReader(Stream stream!!) + ResourceReader(Stream stream) #endif { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + if (!stream.CanRead) + { throw new ArgumentException(SR.Argument_StreamNotReadable); + } _resCache = new Dictionary(FastResourceComparer.Default); _store = new BinaryReader(stream, Encoding.UTF8); diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs index 8b45db60ec5a33..abb3f2ca9afbd7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs @@ -58,9 +58,11 @@ public ResourceSet(Stream stream) ReadResources(); } - public ResourceSet(IResourceReader reader!!) + public ResourceSet(IResourceReader reader) : this() { + ArgumentNullException.ThrowIfNull(reader); + Reader = reader; ReadResources(); } @@ -198,8 +200,10 @@ protected virtual void ReadResources() // to help with some WinRes lifetime issues. } - private object? GetObjectInternal(string name!!) + private object? GetObjectInternal(string name) { + ArgumentNullException.ThrowIfNull(name); + Dictionary? copyOfTable = _table; // Avoid a race with Dispose if (copyOfTable == null) diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs index dd9e6e10e91600..48870e7498eeee 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs @@ -188,11 +188,16 @@ internal RuntimeResourceSet(Stream stream, bool permitDeserialization = false) : _defaultReader = new ResourceReader(stream, _resCache, permitDeserialization); } #else - internal RuntimeResourceSet(IResourceReader reader!!) : + internal RuntimeResourceSet(IResourceReader reader) : // explicitly do not call IResourceReader constructor since it caches all resources // the purpose of RuntimeResourceSet is to lazily load and cache. base() { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + _defaultReader = reader as DeserializingResourceReader ?? throw new ArgumentException(SR.Format(SR.NotSupported_WrongResourceReader_Type, reader.GetType()), nameof(reader)); _resCache = new Dictionary(FastResourceComparer.Default); @@ -260,8 +265,13 @@ private IDictionaryEnumerator GetEnumeratorHelper() return GetObject(key, ignoreCase, false); } - private object? GetObject(string key!!, bool ignoreCase, bool isString) + private object? GetObject(string key, bool ignoreCase, bool isString) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + ResourceReader? reader = _defaultReader; Dictionary? cache = _resCache; if (reader is null || cache is null) diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/SatelliteContractVersionAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/SatelliteContractVersionAttribute.cs index f68c2c317cd869..65350e1301954a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/SatelliteContractVersionAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/SatelliteContractVersionAttribute.cs @@ -21,8 +21,10 @@ namespace System.Resources [EditorBrowsable(EditorBrowsableState.Never)] public sealed class SatelliteContractVersionAttribute : Attribute { - public SatelliteContractVersionAttribute(string version!!) + public SatelliteContractVersionAttribute(string version) { + ArgumentNullException.ThrowIfNull(version); + Version = version; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs index 02afb3e33283d1..1336f00a523fe2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -202,8 +202,10 @@ public void Clear() /// This rule permits the table to invoke createValueCallback outside the internal table lock /// to prevent deadlocks. /// - public TValue GetValue(TKey key, CreateValueCallback createValueCallback!!) + public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { + ArgumentNullException.ThrowIfNull(createValueCallback); + // key is validated by TryGetValue return TryGetValue(key, out TValue? existingValue) ? existingValue : diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs index 3794071092241a..c475b165cd7122 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs @@ -23,8 +23,13 @@ public static class FormattableStringFactory /// Create a from a composite format string and object /// array containing zero or more objects to format. /// - public static FormattableString Create([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format!!, params object?[] arguments!!) => - new ConcreteFormattableString(format, arguments); + public static FormattableString Create([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params object?[] arguments) + { + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(arguments); + + return new ConcreteFormattableString(format, arguments); + } private sealed class ConcreteFormattableString : FormattableString { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index af72ceb7af9933..b11c5c4c181723 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -49,8 +49,11 @@ ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), offset), } [Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - public static void ExecuteCodeWithGuaranteedCleanup(TryCode code!!, CleanupCode backoutCode!!, object? userData) + public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object? userData) { + ArgumentNullException.ThrowIfNull(code); + ArgumentNullException.ThrowIfNull(backoutCode); + bool exceptionThrown = true; try diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs index 7f091be304f082..fba39644d6667e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -198,8 +198,10 @@ private static void ThrowForNonSuccess(Task task) /// The argument is null (Nothing in Visual Basic). /// The awaiter was not properly initialized. /// This method is intended for compiler use rather than use directly in code. - internal static void OnCompletedInternal(Task task, Action continuation!!, bool continueOnCapturedContext, bool flowExecutionContext) + internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { + ArgumentNullException.ThrowIfNull(continuation); + // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs index a190b75504fef7..ea3ddee5539056 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs @@ -36,8 +36,10 @@ public sealed class TupleElementNamesAttribute : Attribute /// transformNames value of { "name1", "name2", null, null, /// null }. /// - public TupleElementNamesAttribute(string?[] transformNames!!) + public TupleElementNamesAttribute(string?[] transformNames) { + ArgumentNullException.ThrowIfNull(transformNames); + _transformNames = transformNames; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs index 03b0be93b195d3..31f425ca2f89be 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -69,8 +69,10 @@ public void UnsafeOnCompleted(Action continuation) /// The action to invoke asynchronously. /// true to flow ExecutionContext; false if flowing is not required. /// The argument is null (Nothing in Visual Basic). - private static void QueueContinuation(Action continuation!!, bool flowContext) + private static void QueueContinuation(Action continuation, bool flowContext) { + ArgumentNullException.ThrowIfNull(continuation); + if (TplEventSource.Log.IsEnabled()) { continuation = OutputCorrelationEtwEvent(continuation); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/ExceptionServices/ExceptionDispatchInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/ExceptionServices/ExceptionDispatchInfo.cs index cc0888dc96b456..6c9b89e0a4cca1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/ExceptionServices/ExceptionDispatchInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/ExceptionServices/ExceptionDispatchInfo.cs @@ -27,8 +27,12 @@ private ExceptionDispatchInfo(Exception exception) // This static method is used to create an instance of ExceptionDispatchInfo for // the specified exception object and save all the required details that maybe // needed to be propagated when the exception is "rethrown" on a different thread. - public static ExceptionDispatchInfo Capture(Exception source!!) => - new ExceptionDispatchInfo(source); + public static ExceptionDispatchInfo Capture(Exception source) + { + ArgumentNullException.ThrowIfNull(source); + + return new ExceptionDispatchInfo(source); + } // Return the exception object represented by this ExceptionDispatchInfo instance public Exception SourceException => _exception; @@ -61,8 +65,10 @@ public void Throw() /// The argument was previously thrown or previously had a stack trace stored into it. /// The exception instance. [StackTraceHidden] - public static Exception SetCurrentStackTrace(Exception source!!) + public static Exception SetCurrentStackTrace(Exception source) { + ArgumentNullException.ThrowIfNull(source); + source.SetCurrentStackTrace(); return source; @@ -86,8 +92,11 @@ public static Exception SetCurrentStackTrace(Exception source!!) /// The caller is responsible for canonicalizing line endings if required. /// can be used to canonicalize line endings. /// - public static Exception SetRemoteStackTrace(Exception source!!, string stackTrace!!) + public static Exception SetRemoteStackTrace(Exception source, string stackTrace) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(stackTrace); + source.SetRemoteStackTrace(stackTrace); return source; diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NoCom.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NoCom.cs index a4111396b053d5..367bd323540546 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NoCom.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NoCom.cs @@ -195,9 +195,19 @@ public static object GetUniqueObjectForIUnknown(IntPtr unknown) throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static bool IsComObject(object o!!) => false; + public static bool IsComObject(object o) + { + ArgumentNullException.ThrowIfNull(o); + + return false; + } - public static bool IsTypeVisibleFromCom(Type t!!) => false; + public static bool IsTypeVisibleFromCom(Type t) + { + ArgumentNullException.ThrowIfNull(t); + + return false; + } [SupportedOSPlatform("windows")] public static int ReleaseComObject(object o) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Unix.cs index c32d0cd2d6edb7..8a02bd29654f5e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Unix.cs @@ -161,8 +161,10 @@ public static unsafe void FreeBSTR(IntPtr ptr) } #pragma warning disable IDE0060 - internal static Type? GetTypeFromProgID(string progID!!, string? server, bool throwOnError) + internal static Type? GetTypeFromProgID(string progID, string? server, bool throwOnError) { + ArgumentNullException.ThrowIfNull(progID); + if (throwOnError) throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Windows.cs index fe9d6f8c59688f..575404c2d6b1fd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.Windows.cs @@ -218,8 +218,10 @@ public static void FreeBSTR(IntPtr ptr) } } - internal static Type? GetTypeFromProgID(string progID!!, string? server, bool throwOnError) + internal static Type? GetTypeFromProgID(string progID, string? server, bool throwOnError) { + ArgumentNullException.ThrowIfNull(progID); + int hr = Interop.Ole32.CLSIDFromProgID(progID, out Guid clsid); if (hr < 0) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs index f2432bb89a1091..bbc79c19effdc2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs @@ -96,20 +96,26 @@ public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen) [RequiresDynamicCode("Marshalling code for the object might not be available. Use the SizeOf overload instead.")] [EditorBrowsable(EditorBrowsableState.Never)] - public static int SizeOf(object structure!!) + public static int SizeOf(object structure) { + ArgumentNullException.ThrowIfNull(structure); + return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } - public static int SizeOf(T structure!!) + public static int SizeOf(T structure) { + ArgumentNullException.ThrowIfNull(structure); + return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } [RequiresDynamicCode("Marshalling code for the object might not be available. Use the SizeOf overload instead.")] [EditorBrowsable(EditorBrowsableState.Never)] - public static int SizeOf(Type t!!) + public static int SizeOf(Type t) { + ArgumentNullException.ThrowIfNull(t); + if (t is not RuntimeType) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); @@ -164,14 +170,18 @@ public static unsafe int Release(IntPtr pUnk) /// an array that is not pinned can cause unexpected results. /// [EditorBrowsable(EditorBrowsableState.Never)] - public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr!!, int index) + public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { + ArgumentNullException.ThrowIfNull(arr); + void* pRawData = Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(arr)); return (IntPtr)((byte*)pRawData + (uint)index * (nuint)arr.GetElementSize()); } - public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(T[] arr!!, int index) + public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(T[] arr, int index) { + ArgumentNullException.ThrowIfNull(arr); + void* pRawData = Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(arr)); return (IntPtr)((byte*)pRawData + (uint)index * (nuint)Unsafe.SizeOf()); } @@ -218,8 +228,10 @@ public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int CopyToNative(source, startIndex, destination, length); } - private static unsafe void CopyToNative(T[] source!!, int startIndex, IntPtr destination, int length) + private static unsafe void CopyToNative(T[] source, int startIndex, IntPtr destination, int length) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(destination); // The rest of the argument validation is done by CopyTo @@ -266,8 +278,10 @@ public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int CopyToManaged(source, destination, startIndex, length); } - private static unsafe void CopyToManaged(IntPtr source, T[] destination!!, int startIndex, int length) + private static unsafe void CopyToManaged(IntPtr source, T[] destination, int startIndex, int length) { + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(source); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -510,15 +524,19 @@ public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val) public static void WriteInt64(IntPtr ptr, long val) => WriteInt64(ptr, 0, val); - public static void Prelink(MethodInfo m!!) + public static void Prelink(MethodInfo m) { + ArgumentNullException.ThrowIfNull(m); + PrelinkCore(m); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This only needs to prelink methods that are actually used")] - public static void PrelinkAll(Type c!!) + public static void PrelinkAll(Type c) { + ArgumentNullException.ThrowIfNull(c); + MethodInfo[] mi = c.GetMethods(); for (int i = 0; i < mi.Length; i++) @@ -542,8 +560,10 @@ public static void StructureToPtr([DisallowNull] T structure, IntPtr ptr, boo [EditorBrowsable(EditorBrowsableState.Never)] public static object? PtrToStructure(IntPtr ptr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] - Type structureType!!) + Type structureType) { + ArgumentNullException.ThrowIfNull(structureType); + if (ptr == IntPtr.Zero) { return null; @@ -1062,8 +1082,10 @@ public static unsafe IntPtr StringToCoTaskMemAnsi(string? s) /// metadata then it is returned otherwise a stable guid is generated based /// on the fully qualified name of the type. /// - public static Guid GenerateGuidForType(Type type!!) + public static Guid GenerateGuidForType(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (type is not RuntimeType) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); @@ -1077,8 +1099,10 @@ public static Guid GenerateGuidForType(Type type!!) /// a PROGID in the metadata then it is returned otherwise a stable PROGID /// is generated based on the fully qualified name of the type. /// - public static string? GenerateProgIdForType(Type type!!) + public static string? GenerateProgIdForType(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (type.IsImport) { throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type)); @@ -1100,8 +1124,10 @@ public static Guid GenerateGuidForType(Type type!!) [RequiresDynamicCode("Marshalling code for the delegate might not be available. Use the GetDelegateForFunctionPointer overload instead.")] [EditorBrowsable(EditorBrowsableState.Never)] - public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t!!) + public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { + ArgumentNullException.ThrowIfNull(t); + ArgumentNullException.ThrowIfNull(ptr); if (t is not RuntimeType) { @@ -1146,8 +1172,10 @@ public static TDelegate GetDelegateForFunctionPointer(IntPtr ptr) [RequiresDynamicCode("Marshalling code for the delegate might not be available. Use the GetFunctionPointerForDelegate overload instead.")] [EditorBrowsable(EditorBrowsableState.Never)] - public static IntPtr GetFunctionPointerForDelegate(Delegate d!!) + public static IntPtr GetFunctionPointerForDelegate(Delegate d) { + ArgumentNullException.ThrowIfNull(d); + return GetFunctionPointerForDelegateInternal(d); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs index 9fad1e49e425d8..6caca636aee18a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs @@ -37,8 +37,10 @@ public static partial class NativeLibrary /// If libraryPath is null /// If the library can't be found. /// If the library is not valid. - public static IntPtr Load(string libraryPath!!) + public static IntPtr Load(string libraryPath) { + ArgumentNullException.ThrowIfNull(libraryPath); + return LoadFromPath(libraryPath, throwOnError: true); } @@ -49,8 +51,10 @@ public static IntPtr Load(string libraryPath!!) /// The out-parameter for the loaded native library handle /// True on successful load, false otherwise /// If libraryPath is null - public static bool TryLoad(string libraryPath!!, out IntPtr handle) + public static bool TryLoad(string libraryPath, out IntPtr handle) { + ArgumentNullException.ThrowIfNull(libraryPath); + handle = LoadFromPath(libraryPath, throwOnError: false); return handle != IntPtr.Zero; } @@ -77,8 +81,11 @@ public static bool TryLoad(string libraryPath!!, out IntPtr handle) /// If assembly is not a RuntimeAssembly /// If the library can't be found. /// If the library is not valid. - public static IntPtr Load(string libraryName!!, Assembly assembly!!, DllImportSearchPath? searchPath) + public static IntPtr Load(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { + ArgumentNullException.ThrowIfNull(libraryName); + ArgumentNullException.ThrowIfNull(assembly); + if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -109,8 +116,11 @@ public static IntPtr Load(string libraryName!!, Assembly assembly!!, DllImportSe /// True on successful load, false otherwise /// If libraryPath or assembly is null /// If assembly is not a RuntimeAssembly - public static bool TryLoad(string libraryName!!, Assembly assembly!!, DllImportSearchPath? searchPath, out IntPtr handle) + public static bool TryLoad(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr handle) { + ArgumentNullException.ThrowIfNull(libraryName); + ArgumentNullException.ThrowIfNull(assembly); + if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -143,9 +153,10 @@ public static void Free(IntPtr handle) /// The address of the symbol /// If handle or name is null /// If the symbol is not found - public static IntPtr GetExport(IntPtr handle, string name!!) + public static IntPtr GetExport(IntPtr handle, string name) { ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(name); return GetSymbol(handle, name, throwOnError: true); } @@ -158,9 +169,11 @@ public static IntPtr GetExport(IntPtr handle, string name!!) /// The out-parameter for the symbol address, if it exists /// True on success, false otherwise /// If handle or name is null - public static bool TryGetExport(IntPtr handle, string name!!, out IntPtr address) + public static bool TryGetExport(IntPtr handle, string name, out IntPtr address) { ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(name); + address = GetSymbol(handle, name, throwOnError: false); return address != IntPtr.Zero; } @@ -185,8 +198,11 @@ public static bool TryGetExport(IntPtr handle, string name!!, out IntPtr address /// The resolver callback to register /// If assembly or resolver is null /// If a resolver is already set for this assembly - public static void SetDllImportResolver(Assembly assembly!!, DllImportResolver resolver!!) + public static void SetDllImportResolver(Assembly assembly, DllImportResolver resolver) { + ArgumentNullException.ThrowIfNull(assembly); + ArgumentNullException.ThrowIfNull(resolver); + if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveC/ObjectiveCMarshal.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveC/ObjectiveCMarshal.cs index cfdac60dff53ee..cbd6108ea4c057 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveC/ObjectiveCMarshal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveC/ObjectiveCMarshal.cs @@ -58,11 +58,16 @@ public static partial class ObjectiveCMarshal /// referenced. Any other value has undefined behavior. /// public static unsafe void Initialize( - delegate* unmanaged beginEndCallback!!, - delegate* unmanaged isReferencedCallback!!, - delegate* unmanaged trackedObjectEnteredFinalization!!, - UnhandledExceptionPropagationHandler unhandledExceptionPropagationHandler!!) + delegate* unmanaged beginEndCallback, + delegate* unmanaged isReferencedCallback, + delegate* unmanaged trackedObjectEnteredFinalization, + UnhandledExceptionPropagationHandler unhandledExceptionPropagationHandler) { + ArgumentNullException.ThrowIfNull(beginEndCallback); + ArgumentNullException.ThrowIfNull(isReferencedCallback); + ArgumentNullException.ThrowIfNull(trackedObjectEnteredFinalization); + ArgumentNullException.ThrowIfNull(unhandledExceptionPropagationHandler); + if (s_unhandledExceptionPropagationHandler != null || !TryInitializeReferenceTracker(beginEndCallback, isReferencedCallback, trackedObjectEnteredFinalization)) { @@ -98,9 +103,11 @@ public static unsafe void Initialize( /// The caller is responsible for freeing the returned . /// public static GCHandle CreateReferenceTrackingHandle( - object obj!!, + object obj, out Span taggedMemory) { + ArgumentNullException.ThrowIfNull(obj); + IntPtr refCountHandle = CreateReferenceTrackingHandleInternal( ObjectHandleOnStack.Create(ref obj), out int memInSizeT, diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.cs index 178d81b5cc7e31..6cec67330022e2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.cs @@ -34,8 +34,12 @@ public sealed partial class PosixSignalRegistration : IDisposable [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] - public static PosixSignalRegistration Create(PosixSignal signal, Action handler!!) => - Register(signal, handler); + public static PosixSignalRegistration Create(PosixSignal signal, Action handler) + { + ArgumentNullException.ThrowIfNull(handler); + + return Register(signal, handler); + } /// Initializes the registration to wrap the specified token. private PosixSignalRegistration(Token token) => _token = token; diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs index 2a0ea5c95bc515..e01e569de38eab 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -212,9 +212,11 @@ public T Read(ulong byteOffset) where T : struct /// The location in the output array to begin writing to. /// The number of value types to read from the input array and to write to the output array. [CLSCompliant(false)] - public void ReadArray(ulong byteOffset, T[] array!!, int index, int count) + public void ReadArray(ulong byteOffset, T[] array, int index, int count) where T : struct { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -299,9 +301,11 @@ public void Write(ulong byteOffset, T value) where T : struct /// The offset in the array to start reading from. /// The number of value types to write. [CLSCompliant(false)] - public void WriteArray(ulong byteOffset, T[] array!!, int index, int count) + public void WriteArray(ulong byteOffset, T[] array, int index, int count) where T : struct { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs index b15601da4214f3..6e523ab9a2e4b8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs @@ -31,8 +31,10 @@ public sealed class AssemblyDependencyResolver private readonly string[] _resourceSearchPaths; private readonly string[] _assemblyDirectorySearchPaths; - public AssemblyDependencyResolver(string componentAssemblyPath!!) + public AssemblyDependencyResolver(string componentAssemblyPath) { + ArgumentNullException.ThrowIfNull(componentAssemblyPath); + string? assemblyPathsList = null; string? nativeSearchPathsList = null; string? resourceSearchPathsList = null; @@ -105,8 +107,10 @@ public AssemblyDependencyResolver(string componentAssemblyPath!!) _assemblyDirectorySearchPaths = new string[1] { Path.GetDirectoryName(componentAssemblyPath)! }; } - public string? ResolveAssemblyToPath(AssemblyName assemblyName!!) + public string? ResolveAssemblyToPath(AssemblyName assemblyName) { + ArgumentNullException.ThrowIfNull(assemblyName); + // Determine if the assembly name is for a satellite assembly or not // This is the same logic as in AssemblyBinder::BindByTpaList in CoreCLR // - If the culture name is non-empty and it's not 'neutral' @@ -151,8 +155,10 @@ public AssemblyDependencyResolver(string componentAssemblyPath!!) return null; } - public string? ResolveUnmanagedDllToPath(string unmanagedDllName!!) + public string? ResolveUnmanagedDllToPath(string unmanagedDllName) { + ArgumentNullException.ThrowIfNull(unmanagedDllName); + string[] searchPaths; if (unmanagedDllName.Contains(Path.DirectorySeparatorChar)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs index d67ae7a2e9aaff..217b57ddd50c5f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -293,8 +293,10 @@ public static IEnumerable All } // Helper to return AssemblyName corresponding to the path of an IL assembly - public static AssemblyName GetAssemblyName(string assemblyPath!!) + public static AssemblyName GetAssemblyName(string assemblyPath) { + ArgumentNullException.ThrowIfNull(assemblyPath); + return AssemblyName.GetAssemblyName(assemblyPath); } @@ -308,8 +310,10 @@ public static AssemblyName GetAssemblyName(string assemblyPath!!) #if !CORERT [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public Assembly LoadFromAssemblyName(AssemblyName assemblyName!!) + public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { + ArgumentNullException.ThrowIfNull(assemblyName); + // Attempt to load the assembly, using the same ordering as static load, in the current load context. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(assemblyName, ref stackMark, this); @@ -319,8 +323,10 @@ public Assembly LoadFromAssemblyName(AssemblyName assemblyName!!) // These methods load assemblies into the current AssemblyLoadContext // They may be used in the implementation of an AssemblyLoadContext derivation [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public Assembly LoadFromAssemblyPath(string assemblyPath!!) + public Assembly LoadFromAssemblyPath(string assemblyPath) { + ArgumentNullException.ThrowIfNull(assemblyPath); + if (PathInternal.IsPartiallyQualified(assemblyPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath)); @@ -335,8 +341,10 @@ public Assembly LoadFromAssemblyPath(string assemblyPath!!) } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public Assembly LoadFromNativeImagePath(string nativeImagePath!!, string? assemblyPath) + public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath) { + ArgumentNullException.ThrowIfNull(nativeImagePath); + if (PathInternal.IsPartiallyQualified(nativeImagePath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, nativeImagePath), nameof(nativeImagePath)); @@ -362,8 +370,10 @@ public Assembly LoadFromStream(Stream assembly) } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] - public Assembly LoadFromStream(Stream assembly!!, Stream? assemblySymbols) + public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols) { + ArgumentNullException.ThrowIfNull(assembly); + int iAssemblyStreamLength = (int)assembly.Length; if (iAssemblyStreamLength <= 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs index 2689acceae7c66..7d9a728f351cc5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -24,8 +24,11 @@ public sealed partial class SerializationInfo private Type _rootType; [CLSCompliant(false)] - public SerializationInfo(Type type!!, IFormatterConverter converter!!) + public SerializationInfo(Type type, IFormatterConverter converter) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(converter); + _rootType = type; _rootTypeName = type.FullName!; _rootTypeAssemblyName = type.Module.Assembly.FullName!; @@ -72,8 +75,10 @@ public string AssemblyName public bool IsAssemblyNameSetExplicit { get; private set; } - public void SetType(Type type!!) + public void SetType(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (!ReferenceEquals(_rootType, type)) { _rootType = type; @@ -121,8 +126,11 @@ private void ExpandArrays() _types = newTypes; } - public void AddValue(string name!!, object? value, Type type!!) + public void AddValue(string name, object? value, Type type) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(type); + AddValueInternal(name, value, type); } @@ -268,8 +276,10 @@ public void UpdateValue(string name, object value, Type type) } } - private int FindElement(string name!!) + private int FindElement(string name) { + ArgumentNullException.ThrowIfNull(name); + if (_nameToIndex.TryGetValue(name, out int index)) { return index; @@ -318,8 +328,10 @@ private int FindElement(string name!!) return _values[index]; } - public object? GetValue(string name, Type type!!) + public object? GetValue(string name, Type type) { + ArgumentNullException.ThrowIfNull(type); + if (type is not RuntimeType) throw new ArgumentException(SR.Argument_MustBeRuntimeType); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs index adaf7f107db40b..410be22aff2de6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs @@ -20,8 +20,10 @@ public sealed class TargetFrameworkAttribute : Attribute private string? _frameworkDisplayName; // The frameworkName parameter is intended to be the string form of a FrameworkName instance. - public TargetFrameworkAttribute(string frameworkName!!) + public TargetFrameworkAttribute(string frameworkName) { + ArgumentNullException.ThrowIfNull(frameworkName); + _frameworkName = frameworkName; } diff --git a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs index 5c0d5889909bcd..1af83dc8ce5921 100644 --- a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs @@ -53,8 +53,10 @@ public override object[] GetCustomAttributes(bool inherit) return CustomAttribute.GetCustomAttributes(this, ObjectType, 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)); @@ -91,8 +93,10 @@ public override MemberInfo[] GetDefaultMembers() public override Type GetElementType() => RuntimeTypeHandle.GetElementType(this); - public override string? GetEnumName(object value!!) + public override string? GetEnumName(object value) { + ArgumentNullException.ThrowIfNull(value); + Type valueType = value.GetType(); if (!(valueType.IsEnum || IsIntegerType(valueType))) @@ -233,16 +237,20 @@ protected override TypeCode GetTypeCodeImpl() protected override bool IsContextfulImpl() => false; - 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)); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } - public override bool IsEnumDefined(object value!!) + public override bool IsEnumDefined(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); @@ -358,9 +366,11 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) [DebuggerHidden] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object? InvokeMember( - string name!!, BindingFlags bindingFlags, Binder? binder, object? target, + string name, BindingFlags bindingFlags, Binder? binder, object? target, object?[]? providedArgs, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParams) { + ArgumentNullException.ThrowIfNull(name); + const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF; const BindingFlags InvocationMask = (BindingFlags)0x0000FF00; const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField; @@ -772,8 +782,10 @@ private static void ThrowIfTypeNeverValidGenericArgument(RuntimeType type) SR.Format(SR.Argument_NeverValidGenericArgument, type)); } - internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments!!, RuntimeType[] genericParameters) + internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParameters) { + ArgumentNullException.ThrowIfNull(genericArguments); + for (int i = 0; i < genericArguments.Length; i++) { ArgumentNullException.ThrowIfNull(genericArguments[i], null); diff --git a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs index 1eada13c2c8d98..a0fa1773f640b2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs @@ -22,8 +22,10 @@ public SecureString() } [CLSCompliant(false)] - public unsafe SecureString(char* value!!, int length) + public unsafe SecureString(char* value, int length) { + ArgumentNullException.ThrowIfNull(value); + if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs b/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs index d900958c0d445c..508498feb7cf4e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -31,16 +31,20 @@ public sealed class SecurityElement //-------------------------- Constructors --------------------------- - public SecurityElement(string tag!!) + public SecurityElement(string tag) { + ArgumentNullException.ThrowIfNull(tag); + if (!IsValidTag(tag)) throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag)); _tag = tag; } - public SecurityElement(string tag!!, string? text) + public SecurityElement(string tag, string? text) { + ArgumentNullException.ThrowIfNull(tag); + if (!IsValidTag(tag)) throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag)); @@ -184,8 +188,11 @@ internal void AddAttributeSafe(string name, string value) _attributes.Add(value); } - public void AddAttribute(string name!!, string value!!) + public void AddAttribute(string name, string value) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + if (!IsValidAttributeName(name)) throw new ArgumentException(SR.Format(SR.Argument_InvalidElementName, name)); @@ -195,8 +202,10 @@ public void AddAttribute(string name!!, string value!!) AddAttributeSafe(name, value); } - public void AddChild(SecurityElement child!!) + public void AddChild(SecurityElement child) { + ArgumentNullException.ThrowIfNull(child); + _children ??= new ArrayList(ChildrenTypical); _children.Add(child); @@ -481,8 +490,10 @@ private void ToString(object obj, Action write) } } - public string? Attribute(string name!!) + public string? Attribute(string name) { + ArgumentNullException.ThrowIfNull(name); + // Note: we don't check for validity here because an // if an invalid name is passed we simply won't find it. if (_attributes == null) @@ -510,8 +521,10 @@ private void ToString(object obj, Action write) return null; } - public SecurityElement? SearchForChildByTag(string tag!!) + public SecurityElement? SearchForChildByTag(string tag) { + ArgumentNullException.ThrowIfNull(tag); + // Go through all the children and see if we can // find the ones that are asked for (matching tags) @@ -527,8 +540,10 @@ private void ToString(object obj, Action write) return null; } - public string? SearchForTextOfTag(string tag!!) + public string? SearchForTextOfTag(string tag) { + ArgumentNullException.ThrowIfNull(tag); + // Search on each child in order and each // child's child, depth-first @@ -548,6 +563,10 @@ private void ToString(object obj, Action write) return null; } - public static SecurityElement? FromString(string xml!!) => default; + public static SecurityElement? FromString(string xml) + { + ArgumentNullException.ThrowIfNull(xml); + return null; + } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs index 8b9aadb0c97c2f..c70e9e52734e84 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs @@ -539,8 +539,10 @@ public bool EndsWith(string value) return EndsWith(value, StringComparison.CurrentCulture); } - public bool EndsWith(string value!!, StringComparison comparisonType) + public bool EndsWith(string value, StringComparison comparisonType) { + ArgumentNullException.ThrowIfNull(value); + if ((object)this == (object)value) { CheckStringComparison(comparisonType); @@ -577,8 +579,10 @@ public bool EndsWith(string value!!, StringComparison comparisonType) } } - public bool EndsWith(string value!!, bool ignoreCase, CultureInfo? culture) + public bool EndsWith(string value, bool ignoreCase, CultureInfo? culture) { + ArgumentNullException.ThrowIfNull(value); + if ((object)this == (object)value) { return true; @@ -927,14 +931,18 @@ static int GetNonRandomizedHashCodeOrdinalIgnoreCaseSlow(string str) // Determines whether a specified string is a prefix of the current instance // - public bool StartsWith(string value!!) + public bool StartsWith(string value) { + ArgumentNullException.ThrowIfNull(value); + return StartsWith(value, StringComparison.CurrentCulture); } [Intrinsic] // Unrolled and vectorized for half-constant input (Ordinal) - public bool StartsWith(string value!!, StringComparison comparisonType) + public bool StartsWith(string value, StringComparison comparisonType) { + ArgumentNullException.ThrowIfNull(value); + if ((object)this == (object)value) { CheckStringComparison(comparisonType); @@ -981,8 +989,10 @@ ref Unsafe.As(ref value.GetRawStringData()), } } - public bool StartsWith(string value!!, bool ignoreCase, CultureInfo? culture) + public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture) { + ArgumentNullException.ThrowIfNull(value); + if ((object)this == (object)value) { return true; diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs index 1661d3ada46fec..7bb34a7f00ceb9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -42,8 +42,10 @@ public static string Concat(object? arg0, object? arg1) => public static string Concat(object? arg0, object? arg1, object? arg2) => Concat(arg0?.ToString(), arg1?.ToString(), arg2?.ToString()); - public static string Concat(params object?[] args!!) + public static string Concat(params object?[] args) { + ArgumentNullException.ThrowIfNull(args); + if (args.Length <= 1) { return args.Length == 0 ? @@ -102,8 +104,10 @@ public static string Concat(params object?[] args!!) return result; } - public static string Concat(IEnumerable values!!) + public static string Concat(IEnumerable values) { + ArgumentNullException.ThrowIfNull(values); + if (typeof(T) == typeof(char)) { // Special-case T==char, as we can handle that case much more efficiently, @@ -183,8 +187,10 @@ public static string Concat(IEnumerable values!!) } } - public static string Concat(IEnumerable values!!) + public static string Concat(IEnumerable values) { + ArgumentNullException.ThrowIfNull(values); + using (IEnumerator en = values.GetEnumerator()) { if (!en.MoveNext()) @@ -361,8 +367,10 @@ public static string Concat(ReadOnlySpan str0, ReadOnlySpan str1, Re return result; } - public static string Concat(params string?[] values!!) + public static string Concat(params string?[] values) { + ArgumentNullException.ThrowIfNull(values); + if (values.Length <= 1) { return values.Length == 0 ? @@ -480,16 +488,20 @@ public static string Format(IFormatProvider? provider, [StringSyntax(StringSynta return FormatHelper(provider, format, new ParamsArray(args)); } - private static string FormatHelper(IFormatProvider? provider, string format!!, ParamsArray args) + private static string FormatHelper(IFormatProvider? provider, string format, ParamsArray args) { + ArgumentNullException.ThrowIfNull(format); + var sb = new ValueStringBuilder(stackalloc char[256]); sb.EnsureCapacity(format.Length + args.Length * 8); sb.AppendFormatHelper(provider, format, args); return sb.ToString(); } - public string Insert(int startIndex, string value!!) + public string Insert(int startIndex, string value) { + ArgumentNullException.ThrowIfNull(value); + if ((uint)startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex)); @@ -538,8 +550,10 @@ public static string Join(char separator, string?[] value, int startIndex, int c public static string Join(string? separator, string?[] value, int startIndex, int count) => JoinCore(separator.AsSpan(), value, startIndex, count); - private static string JoinCore(ReadOnlySpan separator, string?[] value!!, int startIndex, int count) + private static string JoinCore(ReadOnlySpan separator, string?[] value, int startIndex, int count) { + ArgumentNullException.ThrowIfNull(value); + if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -1180,8 +1194,10 @@ private string ReplaceHelper(int oldValueLength, string newValue, ReadOnlySpann is the length of the input string, /// and where r is the length of . /// - public string ReplaceLineEndings(string replacementText!!) + public string ReplaceLineEndings(string replacementText) { + ArgumentNullException.ThrowIfNull(replacementText); + // Early-exit: do we need to do anything at all? // If not, return this string as-is. diff --git a/src/libraries/System.Private.CoreLib/src/System/String.cs b/src/libraries/System.Private.CoreLib/src/System/String.cs index 02e1d10ded23bf..21a286d3a63859 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.cs @@ -81,8 +81,10 @@ private static string Ctor(char[]? value) [DynamicDependency("Ctor(System.Char[],System.Int32,System.Int32)")] public extern String(char[] value, int startIndex, int length); - private static string Ctor(char[] value!!, int startIndex, int length) + private static string Ctor(char[] value, int startIndex, int length) { + ArgumentNullException.ThrowIfNull(value); + if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -305,8 +307,10 @@ private static unsafe string Ctor(ReadOnlySpan value) return result; } - public static string Create(int length, TState state, SpanAction action!!) + public static string Create(int length, TState state, SpanAction action) { + ArgumentNullException.ThrowIfNull(action); + if (length <= 0) { if (length == 0) @@ -368,8 +372,10 @@ public object Clone() [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This API should not be used to create mutable strings. See https://go.microsoft.com/fwlink/?linkid=2084035 for alternatives.")] - public static unsafe string Copy(string str!!) + public static unsafe string Copy(string str) { + ArgumentNullException.ThrowIfNull(str); + string result = FastAllocateString(str.Length); Buffer.Memmove( @@ -385,8 +391,10 @@ public static unsafe string Copy(string str!!) // sourceIndex + count - 1 to the character array buffer, beginning // at destinationIndex. // - public unsafe void CopyTo(int sourceIndex, char[] destination!!, int destinationIndex, int count) + public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { + ArgumentNullException.ThrowIfNull(destination); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount); if (sourceIndex < 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/StringComparer.cs b/src/libraries/System.Private.CoreLib/src/System/StringComparer.cs index d013b563b6f61a..93938b246adf64 100644 --- a/src/libraries/System.Private.CoreLib/src/System/StringComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/StringComparer.cs @@ -42,13 +42,17 @@ public static StringComparer FromComparison(StringComparison comparisonType) }; } - public static StringComparer Create(CultureInfo culture!!, bool ignoreCase) + public static StringComparer Create(CultureInfo culture, bool ignoreCase) { + ArgumentNullException.ThrowIfNull(culture); + return new CultureAwareComparer(culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } - public static StringComparer Create(CultureInfo culture!!, CompareOptions options) + public static StringComparer Create(CultureInfo culture, CompareOptions options) { + ArgumentNullException.ThrowIfNull(culture); + return new CultureAwareComparer(culture, options); } @@ -185,8 +189,10 @@ public int Compare(object? x, object? y) return x.Equals(y); } - public int GetHashCode(object obj!!) + public int GetHashCode(object obj) { + ArgumentNullException.ThrowIfNull(obj); + if (obj is string s) { return GetHashCode(s); @@ -254,8 +260,10 @@ public override bool Equals(string? x, string? y) return _compareInfo.Compare(x, y, _options) == 0; } - public override int GetHashCode(string obj!!) + public override int GetHashCode(string obj) { + ArgumentNullException.ThrowIfNull(obj); + return _compareInfo.GetHashCode(obj, _options); } diff --git a/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs index 63371135495128..712752626fe549 100644 --- a/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs @@ -12,8 +12,10 @@ public static bool IsNormalized(this string strInput) return IsNormalized(strInput, NormalizationForm.FormC); } - public static bool IsNormalized(this string strInput!!, NormalizationForm normalizationForm) + public static bool IsNormalized(this string strInput, NormalizationForm normalizationForm) { + ArgumentNullException.ThrowIfNull(strInput); + return strInput.IsNormalized(normalizationForm); } @@ -23,8 +25,10 @@ public static string Normalize(this string strInput) return Normalize(strInput, NormalizationForm.FormC); } - public static string Normalize(this string strInput!!, NormalizationForm normalizationForm) + public static string Normalize(this string strInput, NormalizationForm normalizationForm) { + ArgumentNullException.ThrowIfNull(strInput); + return strInput.Normalize(normalizationForm); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs index e39722eb679435..ebf07d971271d9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/ASCIIEncoding.cs @@ -77,8 +77,6 @@ internal sealed override void SetDefaultFallbacks() public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters - if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); @@ -107,8 +105,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) public override unsafe int GetByteCount(string chars) { - // Validate input parameters - if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); @@ -127,9 +123,7 @@ public override unsafe int GetByteCount(string chars) [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters - - if (chars == null) + if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } @@ -159,7 +153,7 @@ private unsafe int GetByteCountCommon(char* pChars, int charCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -213,8 +207,6 @@ private protected sealed override unsafe int GetByteCountFast(char* pChars, int public override unsafe int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - // Validate Parameters - if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -263,8 +255,6 @@ public override unsafe int GetBytes(string chars, int charIndex, int charCount, public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - // Validate parameters - if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -303,9 +293,7 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters - - if (chars == null || bytes == null) + if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, @@ -340,9 +328,9 @@ private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -434,8 +422,6 @@ private protected sealed override unsafe int GetBytesWithFallback(ReadOnlySpan= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -547,8 +531,6 @@ private protected sealed override unsafe int GetCharCountFast(byte* pBytes, int public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - // Validate Parameters - if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( @@ -587,8 +569,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, [CLSCompliant(false)] public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters - if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( @@ -624,9 +604,9 @@ private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -717,8 +697,6 @@ private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); @@ -51,19 +51,15 @@ public DecoderFallbackBuffer FallbackBuffer { get { - if (_fallbackBuffer == null) - { - if (_fallback != null) - _fallbackBuffer = _fallback.CreateFallbackBuffer(); - else - _fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); - } + _fallbackBuffer ??= _fallback is not null ? + _fallback.CreateFallbackBuffer() : + DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); return _fallbackBuffer; } } - internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; + internal bool InternalHasFallbackBuffer => _fallbackBuffer is not null; // Reset the Decoder // @@ -98,17 +94,15 @@ public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) [CLSCompliant(false)] - public virtual unsafe int GetCharCount(byte* bytes!!, int count, bool flush) + public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(bytes); if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); byte[] arrbyte = new byte[count]; - int index; - for (index = 0; index < count; index++) + for (int index = 0; index < count; index++) arrbyte[index] = bytes[index]; return GetCharCount(arrbyte, 0, count); @@ -150,8 +144,6 @@ public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // - // WARNING WARNING WARNING - // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. @@ -164,10 +156,11 @@ public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant(false)] - public virtual unsafe int GetChars(byte* bytes!!, int byteCount, - char* chars!!, int charCount, bool flush) + public virtual unsafe int GetChars(byte* bytes, int byteCount, + char* chars, int charCount, bool flush) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -175,8 +168,7 @@ public virtual unsafe int GetChars(byte* bytes!!, int byteCount, // Get the byte array to convert byte[] arrByte = new byte[byteCount]; - int index; - for (index = 0; index < byteCount; index++) + for (int index = 0; index < byteCount; index++) arrByte[index] = bytes[index]; // Get the char array to fill @@ -197,7 +189,7 @@ public virtual unsafe int GetChars(byte* bytes!!, int byteCount, // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of an issue in GetChars - for (index = 0; index < charCount; index++) + for (int index = 0; index < charCount; index++) chars[index] = arrChar[index]; return charCount; @@ -225,11 +217,13 @@ public virtual unsafe int GetChars(ReadOnlySpan bytes, Span chars, b // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) - public virtual void Convert(byte[] bytes!!, int byteIndex, int byteCount, - char[] chars!!, int charIndex, int charCount, bool flush, + public virtual 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -255,7 +249,7 @@ public virtual void Convert(byte[] bytes!!, int byteIndex, int byteCount, { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && - (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); + (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0)); return; } @@ -277,11 +271,13 @@ public virtual void Convert(byte[] bytes!!, int byteIndex, int byteCount, // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] - public virtual unsafe void Convert(byte* bytes!!, int byteCount, - char* chars!!, int charCount, bool flush, + public virtual unsafe void Convert(byte* bytes, int byteCount, + char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -296,7 +292,7 @@ public virtual unsafe void Convert(byte* bytes!!, int byteCount, { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && - (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); + (_fallbackBuffer is null || _fallbackBuffer.Remaining == 0)); return; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs index 7b51214092c7e1..3dea2a410e81c7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderNLS.cs @@ -46,9 +46,10 @@ public override int GetCharCount(byte[] bytes, int index, int count) 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) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -62,9 +63,10 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count, bo return GetCharCount(pBytes + index, count, flush); } - public override unsafe int GetCharCount(byte* bytes!!, int count, bool flush) + public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { - // Validate parameters + ArgumentNullException.ThrowIfNull(bytes); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -74,7 +76,7 @@ public override unsafe int GetCharCount(byte* bytes!!, int count, bool flush) _throwOnOverflow = true; // By default just call the encoding version, no flush by default - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetCharCount(bytes, count, this); } @@ -84,10 +86,12 @@ public override int GetChars(byte[] bytes, int byteIndex, int byteCount, 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) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -110,10 +114,12 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount pChars + charIndex, charCount, flush); } - public override unsafe int GetChars(byte* bytes!!, int byteCount, - char* chars!!, int charCount, bool flush) + public override unsafe int GetChars(byte* bytes, int byteCount, + char* chars, int charCount, bool flush) { - // Validate parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -123,17 +129,19 @@ public override unsafe int GetChars(byte* bytes!!, int byteCount, _throwOnOverflow = true; // By default just call the encodings version - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) - 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -167,10 +175,8 @@ public override unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { - // Validate input parameters - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), - SR.ArgumentNull_Array); + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), @@ -182,7 +188,7 @@ public override unsafe void Convert(byte* bytes, int byteCount, _bytesUsed = 0; // Do conversion - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; @@ -236,7 +242,7 @@ internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan bytes, out int combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charCount = 0; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: @@ -294,7 +300,7 @@ internal int DrainLeftoverDataForGetChars(ReadOnlySpan bytes, Span c bool persistNewCombinedBuffer = false; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs index d19f9c008572a6..4849b738529a4f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs @@ -18,8 +18,10 @@ public DecoderReplacementFallback() : this("?") { } - public DecoderReplacementFallback(string replacement!!) + public DecoderReplacementFallback(string replacement) { + ArgumentNullException.ThrowIfNull(replacement); + // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; foreach (char c in replacement) @@ -91,7 +93,7 @@ public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback) public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer - // We can't call recursively but others might (note, we don't test on last char!!!) + // We can't call recursively but others might (note, we don't test on last char!) if (_fallbackCount >= 1) { ThrowLastBytesRecursive(bytesUnknown); diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs index fd64dac3881d22..6cef4f28a25e9d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoder.cs @@ -36,7 +36,7 @@ public EncoderFallback? Fallback ArgumentNullException.ThrowIfNull(value); // Can't change fallback if buffer is wrong - if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); @@ -51,19 +51,15 @@ public EncoderFallbackBuffer FallbackBuffer { get { - if (_fallbackBuffer == null) - { - if (_fallback != null) - _fallbackBuffer = _fallback.CreateFallbackBuffer(); - else - _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); - } + _fallbackBuffer ??= _fallback is not null ? + _fallback.CreateFallbackBuffer() : + EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); return _fallbackBuffer; } } - internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; + internal bool InternalHasFallbackBuffer => _fallbackBuffer is not null; // Reset the Encoder // @@ -79,8 +75,7 @@ public virtual void Reset() char[] charTemp = Array.Empty(); byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)]; GetBytes(charTemp, 0, 0, byteTemp, 0, true); - if (_fallbackBuffer != null) - _fallbackBuffer.Reset(); + _fallbackBuffer?.Reset(); } // Returns the number of bytes the next call to GetBytes will @@ -96,17 +91,16 @@ public virtual void Reset() // unfortunately for existing overrides, it has to call the [] version, // which is really slow, so avoid this method if you might be calling external encodings. [CLSCompliant(false)] - public virtual unsafe int GetByteCount(char* chars!!, int count, bool flush) + public virtual unsafe int GetByteCount(char* chars, int count, bool flush) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (count < 0) - throw new ArgumentOutOfRangeException(nameof(count), - SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); char[] arrChar = new char[count]; - int index; - for (index = 0; index < count; index++) + for (int index = 0; index < count; index++) arrChar[index] = chars[index]; return GetByteCount(arrChar, 0, count, flush); @@ -159,10 +153,12 @@ public abstract int GetBytes(char[] chars, int charIndex, int charCount, // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant(false)] - public virtual unsafe int GetBytes(char* chars!!, int charCount, - byte* bytes!!, int byteCount, bool flush) + public virtual unsafe int GetBytes(char* chars, int charCount, + byte* bytes, int byteCount, bool flush) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -170,8 +166,7 @@ public virtual unsafe int GetBytes(char* chars!!, int charCount, // Get the char array to convert char[] arrChar = new char[charCount]; - int index; - for (index = 0; index < charCount; index++) + for (int index = 0; index < charCount; index++) arrChar[index] = chars[index]; // Get the byte array to fill @@ -191,7 +186,7 @@ public virtual unsafe int GetBytes(char* chars!!, int charCount, byteCount = result; // Don't copy too many bytes! - for (index = 0; index < byteCount; index++) + for (int index = 0; index < byteCount; index++) bytes[index] = arrByte[index]; return byteCount; @@ -219,11 +214,13 @@ public virtual unsafe int GetBytes(ReadOnlySpan chars, Span bytes, b // Note that if all of the input chars are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) - public virtual void Convert(char[] chars!!, int charIndex, int charCount, - byte[] bytes!!, int byteIndex, int byteCount, bool flush, + public virtual 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -272,14 +269,15 @@ public virtual void Convert(char[] chars!!, int charIndex, int charCount, // that its likely that we didn't consume as many chars as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] - public virtual unsafe void Convert(char* chars!!, int charCount, - byte* bytes!!, int byteCount, bool flush, + public virtual unsafe void Convert(char* chars, int charCount, + byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) - throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), - SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Get ready to do it charsUsed = charCount; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs index 94aa34626abd9d..dc183037910e5d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderNLS.cs @@ -38,13 +38,13 @@ internal EncoderNLS(Encoding encoding) public override void Reset() { _charLeftOver = (char)0; - if (_fallbackBuffer != null) - _fallbackBuffer.Reset(); + _fallbackBuffer?.Reset(); } - 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) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -62,23 +62,26 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count, bo return result; } - public override unsafe int GetByteCount(char* chars!!, int count, bool flush) + public override unsafe int GetByteCount(char* chars, int count, bool flush) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); _mustFlush = flush; _throwOnOverflow = true; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetByteCount(chars, count, this); } - 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -102,26 +105,30 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount pBytes + byteIndex, byteCount, flush); } - public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush) + public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); _mustFlush = flush; _throwOnOverflow = true; - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) - 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -151,11 +158,13 @@ public override unsafe void Convert(char[] chars!!, int charIndex, int charCount // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes - 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) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -166,7 +175,7 @@ public override unsafe void Convert(char* chars!!, int charCount, _charsUsed = 0; // Do conversion - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = _charsUsed; @@ -210,7 +219,7 @@ public Encoding Encoding { get { - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); return _encoding; } } @@ -220,7 +229,7 @@ public Encoding Encoding /// /// States whether a call to must first drain data on this instance. /// - internal bool HasLeftoverData => _charLeftOver != default || (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0); + internal bool HasLeftoverData => _charLeftOver != default || (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0); // Anything left in our encoder? internal virtual bool HasState => _charLeftOver != (char)0; @@ -237,7 +246,7 @@ internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int // as we'd end up consuming any such data and would corrupt whatever Convert call happens // to be in progress. - if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, Encoding.EncodingName, _fallbackBuffer.GetType())); } @@ -281,7 +290,7 @@ internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int { charsConsumed = 1; // consumed the leftover high surrogate + the first char in the input buffer - Debug.Assert(_encoding != null); + Debug.Assert(_encoding is not null); if (_encoding.TryGetByteCount(rune, out int byteCount)) { Debug.Assert(byteCount >= 0, "Encoding shouldn't have returned a negative byte count."); @@ -304,7 +313,7 @@ internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int } // Now tally the number of bytes that would've been emitted as part of fallback. - Debug.Assert(_fallbackBuffer != null); + Debug.Assert(_fallbackBuffer is not null); return _fallbackBuffer.DrainRemainingDataForGetByteCount(); } } @@ -355,7 +364,7 @@ internal bool TryDrainLeftoverDataForGetBytes(ReadOnlySpan chars, Span chars, Span 0) + if (_fallbackBuffer is not null && _fallbackBuffer.Remaining > 0) { return _fallbackBuffer.TryDrainRemainingDataForGetBytes(bytes, out bytesWritten); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs index 376e865d7b15f0..0da440a3019ccc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs @@ -18,8 +18,10 @@ public EncoderReplacementFallback() : this("?") { } - public EncoderReplacementFallback(string replacement!!) + public EncoderReplacementFallback(string replacement) { + ArgumentNullException.ThrowIfNull(replacement); + // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; foreach (char c in replacement) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs index 731a8c92cceeab..a3c4a722103ed5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs @@ -175,8 +175,10 @@ internal virtual void SetDefaultFallbacks() // dstEncoding, and the returned value is a new byte array // containing the result of the conversion. // - public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes!!) + public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { + ArgumentNullException.ThrowIfNull(bytes); + return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length); } @@ -185,9 +187,13 @@ public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] // index index from srcEncoding to dstEncoding, and // returns a new byte array containing the result of the conversion. // - public static byte[] Convert(Encoding srcEncoding!!, Encoding dstEncoding!!, - byte[] bytes!!, int index, int count) + public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, + byte[] bytes, int index, int count) { + ArgumentNullException.ThrowIfNull(srcEncoding); + ArgumentNullException.ThrowIfNull(dstEncoding); + ArgumentNullException.ThrowIfNull(bytes); + return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); } @@ -200,7 +206,7 @@ public static void RegisterProvider(EncodingProvider provider) public static Encoding GetEncoding(int codepage) { Encoding? result = FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(codepage)); - if (result != null) + if (result is not null) return result; switch (codepage) @@ -257,7 +263,7 @@ public static Encoding GetEncoding(int codepage, { Encoding? baseEncoding = FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(codepage, encoderFallback, decoderFallback)); - if (baseEncoding != null) + if (baseEncoding is not null) return baseEncoding; // Get the default encoding (which is cached and read only) @@ -317,7 +323,7 @@ public static Encoding GetEncoding(string name, public static EncodingInfo[] GetEncodings() { Dictionary? result = EncodingProvider.GetEncodingListFromProviders(); - return result == null ? EncodingTable.GetEncodings() : EncodingTable.GetEncodings(result); + return result is null ? EncodingTable.GetEncodings() : EncodingTable.GetEncodings(result); } public virtual byte[] GetPreamble() => Array.Empty(); @@ -326,10 +332,10 @@ public static EncodingInfo[] GetEncodings() private void GetDataItem() { - if (_dataItem == null) + if (_dataItem is null) { _dataItem = EncodingTable.GetCodePageDataItem(_codePage); - if (_dataItem == null) + if (_dataItem is null) { throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, _codePage)); } @@ -343,7 +349,7 @@ public virtual string BodyName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -356,7 +362,7 @@ public virtual string EncodingName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -372,7 +378,7 @@ public virtual string HeaderName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -385,7 +391,7 @@ public virtual string WebName { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -399,7 +405,7 @@ public virtual int WindowsCodePage { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -413,7 +419,7 @@ public virtual bool IsBrowserDisplay { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -427,7 +433,7 @@ public virtual bool IsBrowserSave { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -441,7 +447,7 @@ public virtual bool IsMailNewsDisplay { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -456,7 +462,7 @@ public virtual bool IsMailNewsSave { get { - if (_dataItem == null) + if (_dataItem is null) { GetDataItem(); } @@ -522,14 +528,16 @@ public bool IsReadOnly // Returns the number of bytes required to encode the given character // array. // - public virtual int GetByteCount(char[] chars!!) + public virtual int GetByteCount(char[] chars) { + ArgumentNullException.ThrowIfNull(chars); + return GetByteCount(chars, 0, chars.Length); } public virtual int GetByteCount(string s) { - if (s == null) + if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } @@ -545,8 +553,10 @@ public virtual int GetByteCount(string s) // Returns the number of bytes required to encode a string range. // - public int GetByteCount(string s!!, int index, int count) + public int GetByteCount(string s, int index, int count) { + ArgumentNullException.ThrowIfNull(s); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -571,9 +581,10 @@ public int GetByteCount(string s!!, int index, int count) // which is really slow, so this method should be avoided if you're calling // a 3rd party encoding. [CLSCompliant(false)] - public virtual unsafe int GetByteCount(char* chars!!, int count) + public virtual unsafe int GetByteCount(char* chars, int count) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -594,8 +605,10 @@ public virtual unsafe int GetByteCount(ReadOnlySpan chars) // Returns a byte array containing the encoded representation of the given // character array. // - public virtual byte[] GetBytes(char[] chars!!) + public virtual byte[] GetBytes(char[] chars) { + ArgumentNullException.ThrowIfNull(chars); + return GetBytes(chars, 0, chars.Length); } @@ -624,8 +637,10 @@ public abstract int GetBytes(char[] chars, int charIndex, int charCount, // Returns a byte array containing the encoded representation of the given // string. // - public virtual byte[] GetBytes(string s!!) + public virtual byte[] GetBytes(string s) { + ArgumentNullException.ThrowIfNull(s); + int byteCount = GetByteCount(s); byte[] bytes = new byte[byteCount]; int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0); @@ -636,8 +651,10 @@ public virtual byte[] GetBytes(string s!!) // Returns a byte array containing the encoded representation of the given // string range. // - public byte[] GetBytes(string s!!, int index, int count) + public byte[] GetBytes(string s, int index, int count) { + ArgumentNullException.ThrowIfNull(s); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -670,7 +687,7 @@ public byte[] GetBytes(string s!!, int index, int count) public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (s == null) + if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } @@ -696,10 +713,12 @@ public virtual int GetBytes(string s, int charIndex, int charCount, // when we copy the buffer so that we don't overflow byteCount either. [CLSCompliant(false)] - public virtual unsafe int GetBytes(char* chars!!, int charCount, - byte* bytes!!, int byteCount) + public virtual unsafe int GetBytes(char* chars, int charCount, + byte* bytes, int byteCount) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -741,8 +760,10 @@ public virtual unsafe int GetBytes(ReadOnlySpan chars, Span bytes) // Returns the number of characters produced by decoding the given byte // array. // - public virtual int GetCharCount(byte[] bytes!!) + public virtual int GetCharCount(byte[] bytes) { + ArgumentNullException.ThrowIfNull(bytes); + return GetCharCount(bytes, 0, bytes.Length); } @@ -754,9 +775,10 @@ public virtual int GetCharCount(byte[] bytes!!) // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) [CLSCompliant(false)] - public virtual unsafe int GetCharCount(byte* bytes!!, int count) + public virtual unsafe int GetCharCount(byte* bytes, int count) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(bytes); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -777,8 +799,10 @@ public virtual unsafe int GetCharCount(ReadOnlySpan bytes) // Returns a character array containing the decoded representation of a // given byte array. // - public virtual char[] GetChars(byte[] bytes!!) + public virtual char[] GetChars(byte[] bytes) { + ArgumentNullException.ThrowIfNull(bytes); + return GetChars(bytes, 0, bytes.Length); } @@ -823,10 +847,12 @@ public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant(false)] - public virtual unsafe int GetChars(byte* bytes!!, int byteCount, - char* chars!!, int charCount) + public virtual unsafe int GetChars(byte* bytes, int byteCount, + char* chars, int charCount) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -866,8 +892,10 @@ public virtual unsafe int GetChars(ReadOnlySpan bytes, Span chars) } [CLSCompliant(false)] - public unsafe string GetString(byte* bytes!!, int byteCount) + public unsafe string GetString(byte* bytes, int byteCount) { + ArgumentNullException.ThrowIfNull(bytes); + if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -959,8 +987,10 @@ public virtual bool IsAlwaysNormalized(NormalizationForm form) => // Returns a string containing the decoded representation of a given byte // array. // - public virtual string GetString(byte[] bytes!!) + public virtual string GetString(byte[] bytes) { + ArgumentNullException.ThrowIfNull(bytes); + return GetString(bytes, 0, bytes.Length); } @@ -1038,8 +1068,12 @@ public override int GetHashCode() => /// is full-duplex, the returned will be as well. However, the returned /// is not seekable, even if 's property returns . /// - public static Stream CreateTranscodingStream(Stream innerStream!!, Encoding innerStreamEncoding!!, Encoding outerStreamEncoding!!, bool leaveOpen = false) + public static Stream CreateTranscodingStream(Stream innerStream, Encoding innerStreamEncoding, Encoding outerStreamEncoding, bool leaveOpen = false) { + ArgumentNullException.ThrowIfNull(innerStream); + ArgumentNullException.ThrowIfNull(innerStreamEncoding); + ArgumentNullException.ThrowIfNull(outerStreamEncoding); + // We can't entirely optimize away the case where innerStreamEncoding == outerStreamEncoding. For example, // the Encoding might perform a lossy conversion when it sees invalid data, so we still need to call it // to perform basic validation. It's also possible that somebody subclassed one of the built-in types @@ -1058,9 +1092,9 @@ internal void ThrowBytesOverflow() => internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) { - if (encoder == null || encoder._throwOnOverflow || nothingEncoded) + if (encoder is null || encoder._throwOnOverflow || nothingEncoded) { - if (encoder != null && encoder.InternalHasFallbackBuffer) + if (encoder is not null && encoder.InternalHasFallbackBuffer) encoder.FallbackBuffer.InternalReset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented an encoder fallback with a broken GetMaxCharCount @@ -1086,9 +1120,9 @@ internal void ThrowCharsOverflow() => internal void ThrowCharsOverflow(DecoderNLS? decoder, bool nothingDecoded) { - if (decoder == null || decoder._throwOnOverflow || nothingDecoded) + if (decoder is null || decoder._throwOnOverflow || nothingDecoded) { - if (decoder != null && decoder.InternalHasFallbackBuffer) + if (decoder is not null && decoder.InternalHasFallbackBuffer) decoder.FallbackBuffer.InternalReset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken @@ -1242,10 +1276,9 @@ internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS? decoder, char* char _bytes = byteStart; _byteEnd = byteStart + byteCount; - if (_decoder == null) - _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); - else - _fallbackBuffer = _decoder.FallbackBuffer; + _fallbackBuffer = _decoder is null ? + enc.DecoderFallback.CreateFallbackBuffer() : + _decoder.FallbackBuffer; // If we're getting chars or getting char count we don't expect to have // to remember fallbacks between calls (so it should be empty) @@ -1256,7 +1289,7 @@ internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS? decoder, char* char internal unsafe bool AddChar(char ch, int numBytes) { - if (_chars != null) + if (_chars is not null) { if (_chars >= _charEnd) { @@ -1339,7 +1372,7 @@ internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4) internal unsafe bool Fallback(byte[] byteBuffer) { // Do the fallback and add the data. - if (_chars != null) + if (_chars is not null) { char* pTemp = _chars; if (!_fallbackBuffer.InternalFallback(byteBuffer, _bytes, ref _chars)) @@ -1390,8 +1423,10 @@ internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS? inEncoder, _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; - if (_encoder == null) + if (_encoder is null) + { this.fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); + } else { this.fallbackBuffer = _encoder.FallbackBuffer; @@ -1401,13 +1436,13 @@ internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS? inEncoder, throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback!.GetType())); } - fallbackBuffer.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); + fallbackBuffer.InternalInitialize(_chars, _charEnd, _encoder, _bytes is not null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { Debug.Assert(moreBytesExpected >= 0, "[EncodingByteBuffer.AddByte]expected non-negative moreBytesExpected"); - if (_bytes != null) + if (_bytes is not null) { if (_bytes >= _byteEnd - moreBytesExpected) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs index 6eeddcb74af5aa..54965988061ca1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs @@ -15,8 +15,12 @@ public sealed class EncodingInfo /// The encoding name /// The encoding display name /// - public EncodingInfo(EncodingProvider provider!!, int codePage, string name!!, string displayName!!) : this(codePage, name, displayName) + public EncodingInfo(EncodingProvider provider, int codePage, string name, string displayName) : this(codePage, name, displayName) { + ArgumentNullException.ThrowIfNull(provider); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(displayName); + Provider = provider; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs index b380c2b01ca9c2..11b284f8e04d96 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs @@ -43,8 +43,10 @@ public EncodingProvider() { } public virtual IEnumerable GetEncodings() => Array.Empty(); - internal static void AddProvider(EncodingProvider provider!!) + internal static void AddProvider(EncodingProvider provider) { + ArgumentNullException.ThrowIfNull(provider); + // Few providers are added in a typical app (typically just CodePagesEncodingProvider.Instance), and when they are, // they're generally not added concurrently. So use an optimistic concurrency scheme rather than paying for a lock // object allocation on the startup path. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs index d548f5f405152c..ded8d29edc76c4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs @@ -28,8 +28,10 @@ internal static partial class EncodingTable ** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name. ============================================================================*/ - internal static int GetCodePageFromName(string name!!) + internal static int GetCodePageFromName(string name) { + ArgumentNullException.ThrowIfNull(name); + object? codePageObj = s_nameToCodePage[name]; if (codePageObj != null) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs index eff94125346812..8682764bb938ca 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Latin1Encoding.cs @@ -40,9 +40,7 @@ internal override void SetDefaultFallbacks() public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters - - if (chars == null) + if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } @@ -57,8 +55,6 @@ public override unsafe int GetByteCount(char* chars, int count) public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters - if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); @@ -92,8 +88,6 @@ public override unsafe int GetByteCount(ReadOnlySpan chars) public override unsafe int GetByteCount(string s) { - // Validate input parameters - if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -112,7 +106,7 @@ private unsafe int GetByteCountCommon(char* pChars, int charCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. // Don't bother providing a fallback mechanism; our fast path doesn't use it. @@ -181,9 +175,7 @@ public override int GetMaxByteCount(int charCount) public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters - - if (chars == null || bytes == null) + if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, @@ -202,8 +194,6 @@ public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - // Validate parameters - if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -248,8 +238,6 @@ public override unsafe int GetBytes(ReadOnlySpan chars, Span bytes) public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - // Validate Parameters - if (s is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -289,9 +277,9 @@ private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -328,9 +316,7 @@ private protected sealed override unsafe int GetBytesFast(char* pChars, int char public override unsafe int GetCharCount(byte* bytes, int count) { - // Validate Parameters - - if (bytes == null) + if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes); } @@ -355,8 +341,6 @@ public override int GetCharCount(byte[] bytes) public override int GetCharCount(byte[] bytes, int index, int count) { - // Validate input parameters - if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); @@ -409,8 +393,6 @@ public override int GetMaxCharCount(int byteCount) public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters - if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( @@ -455,8 +437,6 @@ public unsafe override char[] GetChars(byte[] bytes) public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - // Validate Parameters - if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( @@ -490,8 +470,6 @@ public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, public unsafe override char[] GetChars(byte[] bytes, int index, int count) { - // Validate Parameters - if (bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -556,8 +534,6 @@ public unsafe override string GetString(byte[] bytes) public unsafe override string GetString(byte[] bytes, int index, int count) { - // Validate Parameters - if (bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -594,9 +570,9 @@ private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // If we already know ahead of time that the destination buffer isn't large enough to hold // the widened data, fail immediately. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index c5f924ad754b4d..f2527902847d7a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -180,8 +180,10 @@ public StringBuilder(int capacity, int maxCapacity) m_ChunkChars = GC.AllocateUninitializedArray(capacity); } - private StringBuilder(SerializationInfo info!!, StreamingContext context) + private StringBuilder(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + int persistedCapacity = 0; string? persistedString = null; int persistedMaxCapacity = int.MaxValue; @@ -238,8 +240,10 @@ private StringBuilder(SerializationInfo info!!, StreamingContext context) AssertInvariants(); } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + AssertInvariants(); info.AddValue(MaxCapacityField, m_MaxCapacity); info.AddValue(CapacityField, Capacity); @@ -898,8 +902,10 @@ public StringBuilder AppendLine(string? value) return Append(Environment.NewLine); } - public void CopyTo(int sourceIndex, char[] destination!!, int destinationIndex, int count) + public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { + ArgumentNullException.ThrowIfNull(destination); + if (destinationIndex < 0) { throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(destinationIndex))); @@ -1449,8 +1455,10 @@ private static void FormatError() private const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit private const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit - internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string format!!, ParamsArray args) + internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string format, ParamsArray args) { + ArgumentNullException.ThrowIfNull(format); + int pos = 0; int len = format.Length; char ch = '\x0'; diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs index 0efbc0d0345e92..9097bcf4af3530 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF32Encoding.cs @@ -90,9 +90,10 @@ internal override void SetDefaultFallbacks() // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(char[] chars!!, int index, int count) + public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -115,8 +116,7 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count) public override unsafe int GetByteCount(string s) { - // Validate input - if (s == null) + if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } @@ -130,9 +130,10 @@ public override unsafe int GetByteCount(string s) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetByteCount(char* chars!!, int count) + public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(chars); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -145,9 +146,12 @@ public override unsafe int GetByteCount(char* chars!!, int count) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - 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); @@ -177,10 +181,12 @@ public override unsafe int GetBytes(string s!!, int charIndex, int charCount, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -207,9 +213,11 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount) + public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -224,9 +232,10 @@ public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) + public override unsafe int GetCharCount(byte[] bytes, int index, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -247,9 +256,10 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetCharCount(byte* bytes!!, int count) + public override unsafe int GetCharCount(byte* bytes, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -261,10 +271,12 @@ public override unsafe int GetCharCount(byte* bytes!!, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - 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) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -291,9 +303,11 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetChars(byte* bytes!!, int byteCount, char* chars!!, int charCount) + public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -308,9 +322,10 @@ public override unsafe int GetChars(byte* bytes!!, int byteCount, char* chars!!, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe string GetString(byte[] bytes!!, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -330,7 +345,7 @@ public override unsafe string GetString(byte[] bytes!!, int index, int count) // internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null"); + Debug.Assert(chars is not null, "[UTF32Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0"); char* end = chars + count; @@ -343,7 +358,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? en EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; - if (encoder != null) + if (encoder is not null) { highSurrogate = encoder._charLeftOver; fallbackBuffer = encoder.FallbackBuffer; @@ -435,7 +450,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? en } // May have to do our last surrogate - if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) + if ((encoder is null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate charsForFallback = chars; @@ -462,8 +477,8 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? en internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null"); - Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null"); + Debug.Assert(chars is not null, "[UTF32Encoding.GetBytes]chars!=null"); + Debug.Assert(bytes is not null, "[UTF32Encoding.GetBytes]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0"); @@ -478,7 +493,7 @@ internal override unsafe int GetBytes(char* chars, int charCount, EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; - if (encoder != null) + if (encoder is not null) { highSurrogate = encoder._charLeftOver; fallbackBuffer = encoder.FallbackBuffer; @@ -633,7 +648,7 @@ internal override unsafe int GetBytes(char* chars, int charCount, } // May have to do our last surrogate - if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) + if ((encoder is null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate charsForFallback = chars; @@ -645,10 +660,10 @@ internal override unsafe int GetBytes(char* chars, int charCount, } // Fix our encoder if we have one - Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), + Debug.Assert(highSurrogate == 0 || (encoder is not null && !encoder.MustFlush), "[UTF32Encoding.GetBytes]Expected encoder to be flushed."); - if (encoder != null) + if (encoder is not null) { // Remember our left over surrogate (or 0 if flushing) encoder._charLeftOver = highSurrogate; @@ -663,7 +678,7 @@ internal override unsafe int GetBytes(char* chars, int charCount, internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { - Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null"); + Debug.Assert(bytes is not null, "[UTF32Encoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0"); UTF32Decoder? decoder = (UTF32Decoder?)baseDecoder; @@ -681,7 +696,7 @@ internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? ba DecoderFallbackBuffer? fallbackBuffer = null; // See if there's anything in our decoder - if (decoder != null) + if (decoder is not null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; @@ -766,7 +781,7 @@ internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? ba } // See if we have something left over that has to be decoded - if (readCount > 0 && (decoder == null || decoder.MustFlush)) + if (readCount > 0 && (decoder is null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; @@ -806,8 +821,8 @@ internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? ba internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { - Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null"); - Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null"); + Debug.Assert(chars is not null, "[UTF32Encoding.GetChars]chars!=null"); + Debug.Assert(bytes is not null, "[UTF32Encoding.GetChars]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0"); @@ -829,11 +844,11 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, char* charsForFallback; // See if there's anything in our decoder - if (decoder != null) + if (decoder is not null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; - Debug.Assert(baseDecoder != null); + Debug.Assert(baseDecoder is not null); fallbackBuffer = baseDecoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetChars @@ -959,7 +974,7 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, } // See if we have something left over that has to be decoded - if (readCount > 0 && (decoder == null || decoder.MustFlush)) + if (readCount > 0 && (decoder is null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; @@ -1002,7 +1017,7 @@ internal override unsafe int GetChars(byte* bytes, int byteCount, } // Remember any left over stuff, clearing buffer as well for MustFlush - if (decoder != null) + if (decoder is not null) { decoder.iChar = (int)iChar; decoder.readByteCount = readCount; @@ -1151,8 +1166,7 @@ public override void Reset() { this.iChar = 0; this.readByteCount = 0; - if (_fallbackBuffer != null) - _fallbackBuffer.Reset(); + _fallbackBuffer?.Reset(); } // Anything left in our decoder? diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs index a879de211205aa..9c9666141076a5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF7Encoding.cs @@ -133,9 +133,10 @@ public override int GetHashCode() // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(char[] chars!!, int index, int count) + public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -158,8 +159,7 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count) public override unsafe int GetByteCount(string s) { - // Validate input - if (s == null) + if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } @@ -173,9 +173,10 @@ public override unsafe int GetByteCount(string s) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetByteCount(char* chars!!, int count) + public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(chars); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -188,9 +189,12 @@ public override unsafe int GetByteCount(char* chars!!, int count) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - 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); @@ -220,10 +224,12 @@ public override unsafe int GetBytes(string s!!, int charIndex, int charCount, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -250,9 +256,11 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount) + public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -267,9 +275,10 @@ public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) + public override unsafe int GetCharCount(byte[] bytes, int index, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -290,9 +299,10 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetCharCount(byte* bytes!!, int count) + public override unsafe int GetCharCount(byte* bytes, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -304,10 +314,12 @@ public override unsafe int GetCharCount(byte* bytes!!, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - 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) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -334,9 +346,11 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetChars(byte* bytes!!, int byteCount, char* chars!!, int charCount) + public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -351,9 +365,10 @@ public override unsafe int GetChars(byte* bytes!!, int byteCount, char* chars!!, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe string GetString(byte[] bytes!!, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -373,10 +388,10 @@ public override unsafe string GetString(byte[] bytes!!, int index, int count) // internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? baseEncoder) { - Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); + Debug.Assert(chars is not null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); - // Just call GetBytes with bytes == null + // Just call GetBytes with bytes is null return GetBytes(chars, count, null, 0, baseEncoder); } @@ -384,7 +399,7 @@ internal sealed override unsafe int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); - Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); + Debug.Assert(chars is not null, "[UTF7Encoding.GetBytes]chars!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info @@ -398,7 +413,7 @@ internal sealed override unsafe int GetBytes( Encoding.EncodingByteBuffer buffer = new Encoding.EncodingByteBuffer( this, encoder, bytes, byteCount, chars, charCount); - if (encoder != null) + if (encoder is not null) { bits = encoder.bits; bitCount = encoder.bitCount; @@ -482,7 +497,7 @@ internal sealed override unsafe int GetBytes( // Now if we have bits left over we have to encode them. // MustFlush may have been cleared by encoding.ThrowBytesOverflow earlier if converting - if (bitCount >= 0 && (encoder == null || encoder.MustFlush)) + if (bitCount >= 0 && (encoder is null || encoder.MustFlush)) { // Do we have bits we have to stick in? if (bitCount > 0) @@ -508,8 +523,8 @@ internal sealed override unsafe int GetBytes( } // Do we have an encoder we're allowed to use? - // bytes == null if counting, so don't use encoder then - if (bytes != null && encoder != null) + // bytes is null if counting, so don't use encoder then + if (bytes is not null && encoder is not null) { // We already cleared bits & bitcount for mustflush case encoder.bits = bits; @@ -523,7 +538,7 @@ internal sealed override unsafe int GetBytes( internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); - Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); + Debug.Assert(bytes is not null, "[UTF7Encoding.GetCharCount]bytes!=null"); // Just call GetChars with null char* to do counting return GetChars(bytes, count, null, 0, baseDecoder); @@ -533,7 +548,7 @@ internal sealed override unsafe int GetChars( byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); - Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); + Debug.Assert(bytes is not null, "[UTF7Encoding.GetChars]bytes!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder @@ -547,7 +562,7 @@ internal sealed override unsafe int GetChars( int bits = 0; int bitCount = -1; bool firstByte = false; - if (decoder != null) + if (decoder is not null) { bits = decoder.bits; bitCount = decoder.bitCount; @@ -671,8 +686,8 @@ internal sealed override unsafe int GetChars( } } - // Stick stuff in the decoder if we can (chars == null if counting, so don't store decoder) - if (chars != null && decoder != null) + // Stick stuff in the decoder if we can (chars is null if counting, so don't store decoder) + if (chars is not null && decoder is not null) { // MustFlush? (Could've been cleared by ThrowCharsOverflow if Convert & didn't reach end of buffer) if (decoder.MustFlush) @@ -772,8 +787,7 @@ public override void Reset() this.bits = 0; this.bitCount = -1; this.firstByte = false; - if (_fallbackBuffer != null) - _fallbackBuffer.Reset(); + _fallbackBuffer?.Reset(); } // Anything left in our encoder? @@ -801,8 +815,7 @@ public override void Reset() { this.bitCount = -1; this.bits = 0; - if (_fallbackBuffer != null) - _fallbackBuffer.Reset(); + _fallbackBuffer?.Reset(); } // Anything left in our encoder? diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs index 3178c39fcc155b..88ec661423ee58 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UTF8Encoding.cs @@ -128,8 +128,6 @@ internal sealed override void SetDefaultFallbacks() public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters - if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); @@ -158,8 +156,6 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) public override unsafe int GetByteCount(string chars) { - // Validate input parameters - if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); @@ -178,9 +174,7 @@ public override unsafe int GetByteCount(string chars) [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters - - if (chars == null) + if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } @@ -210,7 +204,7 @@ private unsafe int GetByteCountCommon(char* pChars, int charCount) // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. // Don't bother providing a fallback mechanism; our fast path doesn't use it. @@ -261,8 +255,6 @@ private protected sealed override unsafe int GetByteCountFast(char* pChars, int public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { - // Validate Parameters - if (s is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -311,8 +303,6 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - // Validate parameters - if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( @@ -351,9 +341,7 @@ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters - - if (chars == null || bytes == null) + if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, @@ -388,9 +376,9 @@ private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -433,8 +421,6 @@ private protected sealed override unsafe int GetBytesFast(char* pChars, int char public override unsafe int GetCharCount(byte[] bytes, int index, int count) { - // Validate Parameters - if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); @@ -463,9 +449,7 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { - // Validate Parameters - - if (bytes == null) + if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } @@ -496,8 +480,6 @@ public override unsafe int GetCharCount(ReadOnlySpan bytes) public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - // Validate Parameters - if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( @@ -536,8 +518,6 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, [CLSCompliant(false)] public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters - if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( @@ -580,9 +560,9 @@ private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pChars is not null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. @@ -660,8 +640,6 @@ private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan= 0, "Caller shouldn't specify negative length buffer."); - Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); + Debug.Assert(pBytes is not null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. // Don't bother providing a fallback mechanism; our fast path doesn't use it. diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs index 8aa15fe9158f1c..016a8e78dfd456 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/UnicodeEncoding.cs @@ -82,9 +82,10 @@ internal sealed override void SetDefaultFallbacks() // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(char[] chars!!, int index, int count) + public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters + ArgumentNullException.ThrowIfNull(chars); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -107,8 +108,7 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count) public override unsafe int GetByteCount(string s) { - // Validate input - if (s == null) + if (s is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } @@ -122,9 +122,10 @@ public override unsafe int GetByteCount(string s) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetByteCount(char* chars!!, int count) + public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(chars); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -137,9 +138,12 @@ public override unsafe int GetByteCount(char* chars!!, int count) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - 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); @@ -169,10 +173,12 @@ public override unsafe int GetBytes(string s!!, int charIndex, int charCount, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - 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) { - // Validate parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -199,9 +205,11 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount) + public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(chars); + ArgumentNullException.ThrowIfNull(bytes); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -216,9 +224,10 @@ public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) + public override unsafe int GetCharCount(byte[] bytes, int index, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -239,9 +248,10 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetCharCount(byte* bytes!!, int count) + public override unsafe int GetCharCount(byte* bytes, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -253,10 +263,12 @@ public override unsafe int GetCharCount(byte* bytes!!, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - 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) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -283,9 +295,11 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] - public override unsafe int GetChars(byte* bytes!!, int byteCount, char* chars!!, int charCount) + public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + ArgumentNullException.ThrowIfNull(chars); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -300,9 +314,10 @@ public override unsafe int GetChars(byte* bytes!!, int byteCount, char* chars!!, // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe string GetString(byte[] bytes!!, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { - // Validate Parameters + ArgumentNullException.ThrowIfNull(bytes); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -322,7 +337,7 @@ public override unsafe string GetString(byte[] bytes!!, int index, int count) // internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UnicodeEncoding.GetByteCount]chars!=null"); + Debug.Assert(chars is not null, "[UnicodeEncoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); // Start by assuming each char gets 2 bytes @@ -344,7 +359,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder._charLeftOver; @@ -367,7 +382,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder char ch; TryAgain: - while (((ch = (fallbackBuffer == null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) + while (((ch = (fallbackBuffer is null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { // First unwind any fallback if (ch == 0) @@ -475,12 +490,11 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // Fallback the previous surrogate // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false); @@ -509,12 +523,11 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // fallback this one // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false); @@ -542,12 +555,11 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // fallback previous chars // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false); @@ -572,7 +584,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder byteCount -= 2; // If we have to flush, stick it in fallback and try again - if (encoder == null || encoder.MustFlush) + if (encoder is null || encoder.MustFlush) { if (wasHereBefore) { @@ -583,12 +595,11 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder else { // Need to initialize fallback buffer? - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false); @@ -605,7 +616,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check _throwOnOverflow for count) - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end"); // Don't remember fallbackBuffer.encoder for counting @@ -615,10 +626,10 @@ internal sealed override unsafe int GetByteCount(char* chars, int count, Encoder internal sealed override unsafe int GetBytes( char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { - Debug.Assert(chars != null, "[UnicodeEncoding.GetBytes]chars!=null"); + Debug.Assert(chars is not null, "[UnicodeEncoding.GetBytes]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetBytes]byteCount >=0"); Debug.Assert(charCount >= 0, "[UnicodeEncoding.GetBytes]charCount >=0"); - Debug.Assert(bytes != null, "[UnicodeEncoding.GetBytes]bytes!=null"); + Debug.Assert(bytes is not null, "[UnicodeEncoding.GetBytes]bytes!=null"); char charLeftOver = (char)0; char ch; @@ -634,7 +645,7 @@ internal sealed override unsafe int GetBytes( char* charsForFallback; // Get our encoder, but don't clear it yet. - if (encoder != null) + if (encoder is not null) { charLeftOver = encoder._charLeftOver; @@ -652,7 +663,7 @@ internal sealed override unsafe int GetBytes( } TryAgain: - while (((ch = (fallbackBuffer == null) ? + while (((ch = (fallbackBuffer is null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { @@ -761,12 +772,11 @@ internal sealed override unsafe int GetBytes( // Fallback the previous surrogate // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); @@ -790,12 +800,11 @@ internal sealed override unsafe int GetBytes( { // We'll fall back this one // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); @@ -811,7 +820,7 @@ internal sealed override unsafe int GetBytes( if (bytes + 3 >= byteEnd) { // Not enough room to add this surrogate pair - if (fallbackBuffer != null && fallbackBuffer.bFallingBack) + if (fallbackBuffer is not null && fallbackBuffer.bFallingBack) { // These must have both been from the fallbacks. // Both of these MUST have been from a fallback because if the 1st wasn't @@ -860,12 +869,11 @@ internal sealed override unsafe int GetBytes( // fallback previous chars // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); @@ -884,7 +892,7 @@ internal sealed override unsafe int GetBytes( if (bytes + 1 >= byteEnd) { // Couldn't add this char - if (fallbackBuffer != null && fallbackBuffer.bFallingBack) + if (fallbackBuffer is not null && fallbackBuffer.bFallingBack) fallbackBuffer.MovePrevious(); // Not using this fallback char else { @@ -914,7 +922,7 @@ internal sealed override unsafe int GetBytes( if (charLeftOver > 0) { // If we aren't flushing we need to fall this back - if (encoder == null || encoder.MustFlush) + if (encoder is null || encoder.MustFlush) { if (wasHereBefore) { @@ -926,12 +934,11 @@ internal sealed override unsafe int GetBytes( { // If we have to flush, stick it in fallback and try again // Might need to create our fallback buffer - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (encoder == null) - fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = encoder.FallbackBuffer; + fallbackBuffer = encoder is null ? + this.encoderFallback.CreateFallbackBuffer() : + encoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); @@ -950,7 +957,7 @@ internal sealed override unsafe int GetBytes( } // Not flushing, remember it in the encoder - if (encoder != null) + if (encoder is not null) { encoder._charLeftOver = charLeftOver; encoder._charsUsed = (int)(chars - charStart); @@ -958,11 +965,11 @@ internal sealed override unsafe int GetBytes( // Remember charLeftOver if we must, or clear it if we're flushing // (charLeftOver should be 0 if we're flushing) - Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0, + Debug.Assert((encoder is not null && !encoder.MustFlush) || charLeftOver == (char)0, "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing"); - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || - encoder == null || !encoder._throwOnOverflow, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0 || + encoder is null || !encoder._throwOnOverflow, "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting"); return (int)(bytes - byteStart); @@ -970,7 +977,7 @@ internal sealed override unsafe int GetBytes( internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { - Debug.Assert(bytes != null, "[UnicodeEncoding.GetCharCount]bytes!=null"); + Debug.Assert(bytes is not null, "[UnicodeEncoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); UnicodeEncoding.Decoder? decoder = (UnicodeEncoding.Decoder?)baseDecoder; @@ -988,7 +995,7 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder // For fallback we may need a fallback buffer DecoderFallbackBuffer? fallbackBuffer = null; - if (decoder != null) + if (decoder is not null) { lastByte = decoder.lastByte; lastChar = decoder.lastChar; @@ -1128,12 +1135,11 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); @@ -1169,12 +1175,11 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)ch), unchecked((byte)(ch >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); @@ -1208,12 +1213,11 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); @@ -1230,7 +1234,7 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder } // Extra space if we can't use decoder - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { if (lastChar > 0) { @@ -1248,12 +1252,11 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); @@ -1266,12 +1269,11 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder if (lastByte >= 0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); @@ -1289,7 +1291,7 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check _throwOnOverflow for count) - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end"); return charCount; @@ -1298,10 +1300,10 @@ internal sealed override unsafe int GetCharCount(byte* bytes, int count, Decoder internal sealed override unsafe int GetChars( byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { - Debug.Assert(chars != null, "[UnicodeEncoding.GetChars]chars!=null"); + Debug.Assert(chars is not null, "[UnicodeEncoding.GetChars]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UnicodeEncoding.GetChars]charCount >=0"); - Debug.Assert(bytes != null, "[UnicodeEncoding.GetChars]bytes!=null"); + Debug.Assert(bytes is not null, "[UnicodeEncoding.GetChars]bytes!=null"); UnicodeEncoding.Decoder? decoder = (UnicodeEncoding.Decoder?)baseDecoder; @@ -1310,7 +1312,7 @@ internal sealed override unsafe int GetChars( char lastChar = (char)0; // Get our decoder (but don't clear it yet) - if (decoder != null) + if (decoder is not null) { lastByte = decoder.lastByte; lastChar = decoder.lastChar; @@ -1453,12 +1455,11 @@ internal sealed override unsafe int GetChars( { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, charEnd); @@ -1505,12 +1506,11 @@ internal sealed override unsafe int GetChars( { unchecked((byte)ch), unchecked((byte)(ch >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, charEnd); @@ -1567,12 +1567,11 @@ internal sealed override unsafe int GetChars( { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, charEnd); @@ -1615,7 +1614,7 @@ internal sealed override unsafe int GetChars( } // Remember our decoder if we must - if (decoder == null || decoder.MustFlush) + if (decoder is null || decoder.MustFlush) { if (lastChar > 0) { @@ -1632,12 +1631,11 @@ internal sealed override unsafe int GetChars( { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) }; } - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, charEnd); @@ -1671,12 +1669,11 @@ internal sealed override unsafe int GetChars( if (lastByte >= 0) { - if (fallbackBuffer == null) + if (fallbackBuffer is null) { - if (decoder == null) - fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); - else - fallbackBuffer = decoder.FallbackBuffer; + fallbackBuffer = decoder is null ? + this.decoderFallback.CreateFallbackBuffer() : + decoder.FallbackBuffer; // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, charEnd); @@ -1706,7 +1703,7 @@ internal sealed override unsafe int GetChars( End: // Remember our decoder if we must - if (decoder != null) + if (decoder is not null) { Debug.Assert(!decoder.MustFlush || ((lastChar == (char)0) && (lastByte == -1)), "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"); @@ -1718,7 +1715,7 @@ internal sealed override unsafe int GetChars( // Shouldn't have anything in fallback buffer for GetChars // (don't have to check _throwOnOverflow for count or chars) - Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, + Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0, "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end"); return (int)(chars - charStart); @@ -1835,8 +1832,7 @@ public override void Reset() { lastByte = -1; lastChar = '\0'; - if (_fallbackBuffer != null) - _fallbackBuffer.Reset(); + _fallbackBuffer?.Reset(); } // Anything left in our decoder? diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs b/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs index 45c29256b65095..84f355c519744e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/ValueStringBuilder.AppendFormat.cs @@ -43,8 +43,10 @@ public void AppendFormat(IFormatProvider? provider, string format, params object // Copied from StringBuilder, can't be done via generic extension // as ValueStringBuilder is a ref struct and cannot be used in a generic. - internal void AppendFormatHelper(IFormatProvider? provider, string format!!, ParamsArray args) + internal void AppendFormatHelper(IFormatProvider? provider, string format, ParamsArray args) { + ArgumentNullException.ThrowIfNull(format); + // Undocumented exclusive limits on the range for Argument Hole Index and Argument Hole Alignment. const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs index c08ce1a40baba0..a07909669de5e0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs @@ -154,12 +154,15 @@ public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSourc /// The instance that can /// be used to unregister the callback. /// is null. - public CancellationTokenRegistration Register(Action callback!!, bool useSynchronizationContext) => - Register( + public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) + { + ArgumentNullException.ThrowIfNull(callback); + return Register( (Action)(static obj => ((Action)obj!)()), callback, useSynchronizationContext, useExecutionContext: true); + } /// /// Registers a delegate that will be called when this @@ -281,8 +284,10 @@ public CancellationTokenRegistration UnsafeRegister(Action is null. /// The associated CancellationTokenSource has been disposed. - private CancellationTokenRegistration Register(Delegate callback!!, object? state, bool useSynchronizationContext, bool useExecutionContext) + private CancellationTokenRegistration Register(Delegate callback, object? state, bool useSynchronizationContext, bool useExecutionContext) { + ArgumentNullException.ThrowIfNull(callback); + CancellationTokenSource? source = _source; return source != null ? source.Register(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) : diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs index 3fa24dff5057f8..16cdb3350adea6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -754,8 +754,11 @@ public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken /// The CancellationToken instances to observe. /// A that is linked to the source tokens. /// is null. - public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens!!) => - tokens.Length switch + public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens) + { + ArgumentNullException.ThrowIfNull(tokens); + + return tokens.Length switch { 0 => throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty), 1 => CreateLinkedTokenSource(tokens[0]), @@ -765,6 +768,7 @@ public static CancellationTokenSource CreateLinkedTokenSource(params Cancellatio // hence each item cannot be null itself, and reads of the payloads cannot be torn. _ => new LinkedNCancellationTokenSource(tokens), }; + } private sealed class Linked1CancellationTokenSource : CancellationTokenSource { diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs index 35e10264ea5d34..a56996a80aead8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs @@ -31,8 +31,10 @@ public static CompressedStack GetCompressedStack() return new CompressedStack(); } - public static void Run(CompressedStack compressedStack!!, ContextCallback callback, object? state) + public static void Run(CompressedStack compressedStack, ContextCallback callback, object? state) { + ArgumentNullException.ThrowIfNull(compressedStack); + // The original code was not checking for a null callback and would throw NullReferenceException callback(state); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs index d863ba062a428f..01a7aa93f012a0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PreAllocatedOverlapped.cs @@ -91,8 +91,10 @@ public PreAllocatedOverlapped(IOCompletionCallback callback, object? state, obje public static PreAllocatedOverlapped UnsafeCreate(IOCompletionCallback callback, object? state, object? pinData) => new PreAllocatedOverlapped(callback, state, pinData, flowExecutionContext: false); - private PreAllocatedOverlapped(IOCompletionCallback callback!!, object? state, object? pinData, bool flowExecutionContext) + private PreAllocatedOverlapped(IOCompletionCallback callback, object? state, object? pinData, bool flowExecutionContext) { + ArgumentNullException.ThrowIfNull(callback); + _overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, this, flowExecutionContext); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs index 246ed5b92f85a0..675cf7f12f4f8a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs @@ -101,13 +101,13 @@ public WaitHandle AvailableWaitHandle CheckDispose(); // Return it directly if it is not null - if (m_waitHandle != null) + if (m_waitHandle is not null) return m_waitHandle; // lock the count to avoid multiple threads initializing the handle if it is null lock (m_lockObjAndDisposed) { - if (m_waitHandle == null) + if (m_waitHandle is null) { // The initial state for the wait handle is true if the count is greater than zero // false otherwise @@ -288,7 +288,6 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { CheckDispose(); - // Validate input if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( @@ -347,9 +346,9 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) // If there are any async waiters, for fairness we'll get in line behind // then by translating our synchronous wait into an asynchronous one that we // then block on (once we've released the lock). - if (m_asyncHead != null) + if (m_asyncHead is not null) { - Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't"); + Debug.Assert(m_asyncTail is not null, "tail should not be null if head isn't"); asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken); } // There are no async waiters, so we can proceed with normal synchronous waiting. @@ -388,13 +387,13 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) waitSuccessful = true; m_currentCount--; } - else if (oce != null) + else if (oce is not null) { throw oce; } // Exposing wait handle which is lazily initialized if needed - if (m_waitHandle != null && m_currentCount == 0) + if (m_waitHandle is not null && m_currentCount == 0) { m_waitHandle.Reset(); } @@ -419,7 +418,7 @@ public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) // wait, and whether we successfully acquired the semaphore is // stored in waitSuccessful. - return (asyncWaitTask != null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful; + return (asyncWaitTask is not null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful; } /// @@ -599,7 +598,6 @@ public Task WaitAsync(int millisecondsTimeout, CancellationToken cancellat { CheckDispose(); - // Validate input if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( @@ -616,7 +614,7 @@ public Task WaitAsync(int millisecondsTimeout, CancellationToken cancellat if (m_currentCount > 0) { --m_currentCount; - if (m_waitHandle != null && m_currentCount == 0) m_waitHandle.Reset(); + if (m_waitHandle is not null && m_currentCount == 0) m_waitHandle.Reset(); return Task.FromResult(true); } else if (millisecondsTimeout == 0) @@ -648,15 +646,15 @@ private TaskNode CreateAndAddAsyncWaiter() var task = new TaskNode(); // Add it to the linked list - if (m_asyncHead == null) + if (m_asyncHead is null) { - Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail"); + Debug.Assert(m_asyncTail is null, "If head is null, so too should be tail"); m_asyncHead = task; m_asyncTail = task; } else { - Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail"); + Debug.Assert(m_asyncTail is not null, "If head is not null, neither should be tail"); m_asyncTail.Next = task; task.Prev = m_asyncTail; m_asyncTail = task; @@ -671,18 +669,18 @@ private TaskNode CreateAndAddAsyncWaiter() /// true if the waiter was in the list; otherwise, false. private bool RemoveAsyncWaiter(TaskNode task) { - Debug.Assert(task != null, "Expected non-null task"); + Debug.Assert(task is not null, "Expected non-null task"); Debug.Assert(Monitor.IsEntered(m_lockObjAndDisposed), "Requires the lock be held"); // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. - bool wasInList = m_asyncHead == task || task.Prev != null; + bool wasInList = m_asyncHead == task || task.Prev is not null; // Remove it from the linked list - if (task.Next != null) task.Next.Prev = task.Prev; - if (task.Prev != null) task.Prev.Next = task.Next; + if (task.Next is not null) task.Next.Prev = task.Prev; + if (task.Prev is not null) task.Prev.Next = task.Next; if (m_asyncHead == task) m_asyncHead = task.Next; if (m_asyncTail == task) m_asyncTail = task.Prev; - Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null"); + Debug.Assert((m_asyncHead is null) == (m_asyncTail is null), "Head is null iff tail is null"); // Make sure not to leak task.Next = task.Prev = null; @@ -698,7 +696,7 @@ private bool RemoveAsyncWaiter(TaskNode task) /// The task to return to the caller. private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) { - Debug.Assert(asyncWaiter != null, "Waiter should have been constructed"); + Debug.Assert(asyncWaiter is not null, "Waiter should have been constructed"); Debug.Assert(Monitor.IsEntered(m_lockObjAndDisposed), "Requires the lock be held"); await new ConfiguredNoThrowAwaiter(asyncWaiter.WaitAsync(TimeSpan.FromMilliseconds(millisecondsTimeout), cancellationToken)); @@ -776,7 +774,6 @@ public int Release(int releaseCount) { CheckDispose(); - // Validate input if (releaseCount < 1) { throw new ArgumentOutOfRangeException( @@ -828,11 +825,11 @@ public int Release(int releaseCount) // asynchronous waiters, we assume that all synchronous waiters will eventually // acquire the semaphore. That could be a faulty assumption if those synchronous // waits are canceled, but the wait code path will handle that. - if (m_asyncHead != null) + if (m_asyncHead is not null) { - Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null"); + Debug.Assert(m_asyncTail is not null, "tail should not be null if head isn't null"); int maxAsyncToRelease = currentCount - waitCount; - while (maxAsyncToRelease > 0 && m_asyncHead != null) + while (maxAsyncToRelease > 0 && m_asyncHead is not null) { --currentCount; --maxAsyncToRelease; @@ -846,7 +843,7 @@ public int Release(int releaseCount) m_currentCount = currentCount; // Exposing wait handle if it is not null - if (m_waitHandle != null && returnCount == 0 && currentCount > 0) + if (m_waitHandle is not null && returnCount == 0 && currentCount > 0) { m_waitHandle.Set(); } @@ -885,7 +882,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { WaitHandle? wh = m_waitHandle; - if (wh != null) + if (wh is not null) { wh.Dispose(); m_waitHandle = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs index 984ba13db2d02e..0ec52392c2dde3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs @@ -42,8 +42,10 @@ public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTime } [CLSCompliant(false)] - protected static int WaitHelper(IntPtr[] waitHandles!!, bool waitAll, int millisecondsTimeout) + protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { + ArgumentNullException.ThrowIfNull(waitHandles); + return WaitHandle.WaitMultipleIgnoringSyncContext(waitHandles, waitAll, millisecondsTimeout); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index 380fc307a9fb65..51f6bc0f0ce214 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -96,8 +96,10 @@ public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConc /// The target scheduler on which this pair should execute. /// The maximum number of tasks to run concurrently. /// The maximum number of tasks to process for each underlying scheduled task used by the pair. - public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler!!, int maxConcurrencyLevel, int maxItemsPerTask) + public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { + ArgumentNullException.ThrowIfNull(taskScheduler); + if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs index cfb1eb45a96889..efeb2dc1204b5a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs @@ -1602,7 +1602,6 @@ internal static Task ContinueWhenAllImpl(Task[], TResult>? continuationFunction, Action[]>? continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { - // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); // ArgumentNullException of continuationFunction or continuationAction is checked by the caller @@ -1646,7 +1645,6 @@ internal static Task ContinueWhenAllImpl(Task[] tasks, Func? continuationFunction, Action? continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { - // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); // ArgumentNullException of continuationFunction or continuationAction is checked by the caller @@ -1969,7 +1967,6 @@ internal static Task ContinueWhenAnyImpl(Task[] tasks, Func? continuationFunction, Action? continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { - // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); @@ -2021,7 +2018,6 @@ internal static Task ContinueWhenAnyImpl(Task, TResult>? continuationFunction, Action>? continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { - // check arguments TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs index 12321fbec693db..2ce208737fc65d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs @@ -115,8 +115,10 @@ private void ThrowForFailedGetResult(short token) /// The state object to pass to when it's invoked. /// Opaque value that was provided to the 's constructor. /// The flags describing the behavior of the continuation. - public void OnCompleted(Action continuation!!, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) { + ArgumentNullException.ThrowIfNull(continuation); + ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index 28ba77968d9918..06c8f8cce72e1b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -5444,7 +5444,6 @@ public static Task Run(Func function) /// public static Task Run(Func function, CancellationToken cancellationToken) { - // Check arguments if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); // Short-circuit if we are given a pre-canceled token @@ -5489,7 +5488,6 @@ public static Task Run(Func?> function) /// public static Task Run(Func?> function, CancellationToken cancellationToken) { - // Check arguments if (function == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); // Short-circuit if we are given a pre-canceled token @@ -6238,10 +6236,16 @@ public static Task WhenAny(params Task[] tasks) /// /// The or argument was null. /// - public static Task WhenAny(Task task1!!, Task task2!!) => - task1.IsCompleted ? FromResult(task1) : - task2.IsCompleted ? FromResult(task2) : - new TwoTaskWhenAnyPromise(task1, task2); + public static Task WhenAny(Task task1, Task task2) + { + ArgumentNullException.ThrowIfNull(task1); + ArgumentNullException.ThrowIfNull(task2); + + return + task1.IsCompleted ? FromResult(task1) : + task2.IsCompleted ? FromResult(task2) : + new TwoTaskWhenAnyPromise(task1, task2); + } /// A promise type used by WhenAny to wait on exactly two tasks. /// Specifies the type of the task. @@ -6430,10 +6434,16 @@ public static Task> WhenAny(params Task[] tasks) /// /// The or argument was null. /// - public static Task> WhenAny(Task task1!!, Task task2!!) => - task1.IsCompleted ? FromResult(task1) : - task2.IsCompleted ? FromResult(task2) : - new TwoTaskWhenAnyPromise>(task1, task2); + public static Task> WhenAny(Task task1, Task task2) + { + ArgumentNullException.ThrowIfNull(task1); + ArgumentNullException.ThrowIfNull(task2); + + return + task1.IsCompleted ? FromResult(task1) : + task2.IsCompleted ? FromResult(task2) : + new TwoTaskWhenAnyPromise>(task1, task2); + } /// /// Creates a task that will complete when any of the supplied tasks have completed. diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs index 05704234f6cb97..8489b823c99cbe 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskExtensions.cs @@ -9,23 +9,33 @@ public static class TaskExtensions /// Creates a proxy that represents the asynchronous operation of a . /// The to unwrap. /// A that represents the asynchronous operation of the provided . - public static Task Unwrap(this Task task!!) => + public static Task Unwrap(this Task task) + { + ArgumentNullException.ThrowIfNull(task); + // If the task hasn't completed or was faulted/canceled, wrap it in an unwrap promise. Otherwise, // it completed successfully. Return its inner task to avoid unnecessary wrapping, or if the inner // task is null, return a canceled task to match the same semantics as CreateUnwrapPromise. - !task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise(task, lookForOce: false) : - task.Result ?? - Task.FromCanceled(new CancellationToken(true)); + return + !task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise(task, lookForOce: false) : + task.Result ?? + Task.FromCanceled(new CancellationToken(true)); + } /// Creates a proxy that represents the asynchronous operation of a wrapped . /// The wrapped to unwrap. /// A that represents the asynchronous operation of the provided wrapped . - public static Task Unwrap(this Task> task!!) => + public static Task Unwrap(this Task> task) + { + ArgumentNullException.ThrowIfNull(task); + // If the task hasn't completed or was faulted/canceled, wrap it in an unwrap promise. Otherwise, // it completed successfully. Return its inner task to avoid unnecessary wrapping, or if the inner // task is null, return a canceled task to match the same semantics as CreateUnwrapPromise. - !task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise(task, lookForOce: false) : - task.Result ?? - Task.FromCanceled(new CancellationToken(true)); + return + !task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise(task, lookForOce: false) : + task.Result ?? + Task.FromCanceled(new CancellationToken(true)); + } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs index cdbf52ed8099f3..d62e3c93753c4b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs @@ -1695,8 +1695,10 @@ internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) /// array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!) + public Task ContinueWhenAll(Task[] tasks, Action continuationAction) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1721,8 +1723,10 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!) /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!, CancellationToken cancellationToken) + public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1753,8 +1757,10 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!, C /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!, TaskContinuationOptions continuationOptions) + public Task ContinueWhenAll(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1795,9 +1801,11 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!, T /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!, CancellationToken cancellationToken, + public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1818,8 +1826,10 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction!!, C /// array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction!!) + public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1846,9 +1856,11 @@ public Task ContinueWhenAll(Task[] tasks, /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction!!, + public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1880,9 +1892,11 @@ public Task ContinueWhenAll(Task[] tasks, /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction!!, + public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1924,9 +1938,11 @@ public Task ContinueWhenAll(Task[] tasks, /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction!!, + public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1950,8 +1966,10 @@ public Task ContinueWhenAll(Task[] tasks, /// array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAll(Task[] tasks, Func continuationFunction!!) + public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1981,8 +1999,10 @@ public Task ContinueWhenAll(Task[] tasks, FuncThe provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAll(Task[] tasks, Func continuationFunction!!, CancellationToken cancellationToken) + public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2017,8 +2037,10 @@ public Task ContinueWhenAll(Task[] tasks, FuncTaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Func continuationFunction!!, TaskContinuationOptions continuationOptions) + public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2063,9 +2085,11 @@ public Task ContinueWhenAll(Task[] tasks, FuncTaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Func continuationFunction!!, CancellationToken cancellationToken, + public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2091,8 +2115,10 @@ public Task ContinueWhenAll(Task[] tasks, Func array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction!!) + public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2122,9 +2148,11 @@ public Task ContinueWhenAll(TaskThe provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction!!, + public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2160,9 +2188,11 @@ public Task ContinueWhenAll(TaskTaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction!!, + public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2208,9 +2238,11 @@ public Task ContinueWhenAll(TaskTaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAll. /// - public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction!!, + public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2382,8 +2414,10 @@ internal static void CommonCWAnyLogicCleanup(Task continuation) /// array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!) + public Task ContinueWhenAny(Task[] tasks, Action continuationAction) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2408,8 +2442,10 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!) /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!, CancellationToken cancellationToken) + public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2440,8 +2476,10 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!, Can /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!, TaskContinuationOptions continuationOptions) + public Task ContinueWhenAny(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2482,9 +2520,11 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!, Tas /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!, CancellationToken cancellationToken, + public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -2509,8 +2549,10 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction!!, Can /// array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAny(Task[] tasks, Func continuationFunction!!) + public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2539,8 +2581,10 @@ public Task ContinueWhenAny(Task[] tasks, Func /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAny(Task[] tasks, Func continuationFunction!!, CancellationToken cancellationToken) + public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2575,8 +2619,10 @@ public Task ContinueWhenAny(Task[] tasks, Func /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Func continuationFunction!!, TaskContinuationOptions continuationOptions) + public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2621,9 +2667,11 @@ public Task ContinueWhenAny(Task[] tasks, Func /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Func continuationFunction!!, CancellationToken cancellationToken, + public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2648,8 +2696,10 @@ public Task ContinueWhenAny(Task[] tasks, Func /// array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction!!) + public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2679,9 +2729,11 @@ public Task ContinueWhenAny(TaskThe provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction!!, + public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2717,9 +2769,11 @@ public Task ContinueWhenAny(TaskTaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction!!, + public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2765,9 +2819,11 @@ public Task ContinueWhenAny(TaskTaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction!!, + public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationFunction); + return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2789,8 +2845,10 @@ public Task ContinueWhenAny(Task array contains a null value. /// The exception that is thrown when the /// array is empty. - public Task ContinueWhenAny(Task[] tasks, Action> continuationAction!!) + public Task ContinueWhenAny(Task[] tasks, Action> continuationAction) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2816,9 +2874,11 @@ public Task ContinueWhenAny(Task[] tasks, /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWhenAny(Task[] tasks, Action> continuationAction!!, + public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2850,9 +2910,11 @@ public Task ContinueWhenAny(Task[] tasks, /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Action> continuationAction!!, + public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, TaskContinuationOptions continuationOptions) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2894,16 +2956,20 @@ public Task ContinueWhenAny(Task[] tasks, /// which constrain for which TaskStatus states a continuation /// will be executed, are illegal with ContinueWhenAny. /// - public Task ContinueWhenAny(Task[] tasks, Action> continuationAction!!, + public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { + ArgumentNullException.ThrowIfNull(continuationAction); + return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } // Check task array and return a defensive copy. // Used with ContinueWhenAll()/ContinueWhenAny(). - internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks!!) + internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { + ArgumentNullException.ThrowIfNull(tasks); + if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); @@ -2919,8 +2985,10 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks!!) return tasksCopy; } - internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks!!) + internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { + ArgumentNullException.ThrowIfNull(tasks); + if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs index 35c8e0376da413..3d4b2d480e6a2d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -107,15 +107,19 @@ private void InitializeCulture() } } - public Thread(ThreadStart start!!) + public Thread(ThreadStart start) { + ArgumentNullException.ThrowIfNull(start); + _startHelper = new StartHelper(start); Initialize(); } - public Thread(ThreadStart start!!, int maxStackSize) + public Thread(ThreadStart start, int maxStackSize) { + ArgumentNullException.ThrowIfNull(start); + if (maxStackSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -126,15 +130,19 @@ public Thread(ThreadStart start!!, int maxStackSize) Initialize(); } - public Thread(ParameterizedThreadStart start!!) + public Thread(ParameterizedThreadStart start) { + ArgumentNullException.ThrowIfNull(start); + _startHelper = new StartHelper(start); Initialize(); } - public Thread(ParameterizedThreadStart start!!, int maxStackSize) + public Thread(ParameterizedThreadStart start, int maxStackSize) { + ArgumentNullException.ThrowIfNull(start); + if (maxStackSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -230,8 +238,10 @@ private void RequireCurrentThread() } } - private void SetCultureOnUnstartedThread(CultureInfo value!!, bool uiCulture) + private void SetCultureOnUnstartedThread(CultureInfo value, bool uiCulture) { + ArgumentNullException.ThrowIfNull(value); + StartHelper? startHelper = _startHelper; // This check is best effort to catch common user errors only. It won't catch all posssible race @@ -604,8 +614,10 @@ public static void FreeNamedSlot(string name) } } - private static ThreadLocal GetThreadLocal(LocalDataStoreSlot slot!!) + private static ThreadLocal GetThreadLocal(LocalDataStoreSlot slot) { + ArgumentNullException.ThrowIfNull(slot); + Debug.Assert(slot.Data != null); return slot.Data; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs index ec6a28efbb5ecb..35df3aa326b581 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs @@ -89,8 +89,10 @@ public ThreadLocal(bool trackAllValues) /// /// is a null reference (Nothing in Visual Basic). /// - public ThreadLocal(Func valueFactory!!) + public ThreadLocal(Func valueFactory) { + ArgumentNullException.ThrowIfNull(valueFactory); + Initialize(valueFactory, false); } @@ -106,8 +108,10 @@ public ThreadLocal(Func valueFactory!!) /// /// is a null reference (Nothing in Visual Basic). /// - public ThreadLocal(Func valueFactory!!, bool trackAllValues) + public ThreadLocal(Func valueFactory, bool trackAllValues) { + ArgumentNullException.ThrowIfNull(valueFactory); + Initialize(valueFactory, trackAllValues); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.Windows.cs index 6219045425cf34..da8e83c5b009e9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.Windows.cs @@ -37,8 +37,10 @@ public static bool BindHandle(IntPtr osHandle) } [SupportedOSPlatform("windows")] - public static bool BindHandle(SafeHandle osHandle!!) + public static bool BindHandle(SafeHandle osHandle) { + ArgumentNullException.ThrowIfNull(osHandle); + bool mustReleaseSafeHandle = false; try { diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs index b85726bbc0ea7d..2b62413a048278 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs @@ -97,13 +97,16 @@ internal static object GetOrCreateThreadLocalCompletionCountObject() => PortableThreadPool.ThreadPoolInstance.GetOrCreateThreadLocalCompletionCountObject(); 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 registeredHandle = new RegisteredWaitHandle( waitObject, new _ThreadPoolWaitOrTimerCallback(callBack, state, flowExecutionContext), diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.cs index 3847cb8431f685..77da0abb27f2bb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.cs @@ -71,8 +71,10 @@ private ThreadPoolBoundHandle(SafeHandle handle) /// does not take ownership of , /// it remains the responsibility of the caller to call . /// - public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) + public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { + ArgumentNullException.ThrowIfNull(handle); + if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); @@ -172,8 +174,10 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) public unsafe NativeOverlapped* UnsafeAllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData) => AllocateNativeOverlapped(callback, state, pinData, flowExecutionContext: false); - private unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback!!, object? state, object? pinData, bool flowExecutionContext) + private unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData, bool flowExecutionContext) { + ArgumentNullException.ThrowIfNull(callback); + EnsureNotDisposed(); ThreadPoolBoundHandleOverlapped overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, preAllocated: null, flowExecutionContext); @@ -210,8 +214,10 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) /// /// [CLSCompliant(false)] - public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated!!) + public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { + ArgumentNullException.ThrowIfNull(preAllocated); + EnsureNotDisposed(); preAllocated.AddRef(); @@ -257,8 +263,10 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) /// This method was called after the was disposed. /// [CLSCompliant(false)] - public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped!!) + public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { + ArgumentNullException.ThrowIfNull(overlapped); + // Note: we explicitly allow FreeNativeOverlapped calls after the ThreadPoolBoundHandle has been Disposed. ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped); @@ -289,8 +297,10 @@ public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped!!) /// is . /// [CLSCompliant(false)] - public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped!!) + public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped) { + ArgumentNullException.ThrowIfNull(overlapped); + ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped); Debug.Assert(wrapper._boundHandle != null); return wrapper._userState; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs index 9c22e1fb3019ce..9b7d873dc99295 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -94,7 +94,12 @@ private sealed class TimerQueueDebuggerTypeProxy { private readonly TimerQueue _queue; - public TimerQueueDebuggerTypeProxy(TimerQueue queue!!) => _queue = queue; + public TimerQueueDebuggerTypeProxy(TimerQueue queue) + { + ArgumentNullException.ThrowIfNull(queue); + + _queue = queue; + } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public TimerQueueTimer[] Items => new List(_queue.GetTimersForDebugger()).ToArray(); @@ -881,12 +886,14 @@ public Timer(TimerCallback callback) } [MemberNotNull(nameof(_timer))] - private void TimerSetup(TimerCallback callback!!, + private void TimerSetup(TimerCallback callback, object? state, uint dueTime, uint period, bool flowExecutionContext = true) { + ArgumentNullException.ThrowIfNull(callback); + _timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, flowExecutionContext)); } @@ -945,8 +952,10 @@ public static long ActiveCount } } - public bool Dispose(WaitHandle notifyObject!!) + public bool Dispose(WaitHandle notifyObject) { + ArgumentNullException.ThrowIfNull(notifyObject); + return _timer.Close(notifyObject); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index ea799f79acb24b..4f8d86d413c2f3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -238,8 +238,10 @@ private static void ObtainSafeWaitHandles( } } - private static int WaitMultiple(WaitHandle[] waitHandles!!, bool waitAll, int millisecondsTimeout) + private static int WaitMultiple(WaitHandle[] waitHandles, bool waitAll, int millisecondsTimeout) { + ArgumentNullException.ThrowIfNull(waitHandles); + return WaitMultiple(new ReadOnlySpan(waitHandles), waitAll, millisecondsTimeout); } @@ -348,8 +350,11 @@ private static int WaitAnyMultiple(ReadOnlySpan safeWaitHandles, return waitResult; } - private static bool SignalAndWait(WaitHandle toSignal!!, WaitHandle toWaitOn!!, int millisecondsTimeout) + private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout) { + ArgumentNullException.ThrowIfNull(toSignal); + ArgumentNullException.ThrowIfNull(toWaitOn); + if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs index 9b6712c81109b3..5fc146dd8a6ef2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs @@ -12,15 +12,23 @@ public static class WaitHandleExtensions /// /// The to operate on. /// A representing the native operating system handle. - public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle!!) => - waitHandle.SafeWaitHandle; + public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle) + { + ArgumentNullException.ThrowIfNull(waitHandle); + + return waitHandle.SafeWaitHandle; + } /// /// Sets the native operating system handle /// /// The to operate on. /// A representing the native operating system handle. - public static void SetSafeWaitHandle(this WaitHandle waitHandle!!, SafeWaitHandle? value) => + public static void SetSafeWaitHandle(this WaitHandle waitHandle, SafeWaitHandle? value) + { + ArgumentNullException.ThrowIfNull(waitHandle); + waitHandle.SafeWaitHandle = value; + } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs index 6650d80948c704..12dbeb4fdb1bb5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs @@ -260,8 +260,10 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("DateStart", _dateStart); // Do not rename (binary serialization) info.AddValue("DateEnd", _dateEnd); // Do not rename (binary serialization) info.AddValue("DaylightDelta", _daylightDelta); // Do not rename (binary serialization) @@ -271,8 +273,10 @@ void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext cont info.AddValue("NoDaylightTransitions", _noDaylightTransitions); // Do not rename (binary serialization) } - private AdjustmentRule(SerializationInfo info!!, StreamingContext context) + private AdjustmentRule(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime))!; // Do not rename (binary serialization) _dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime))!; // Do not rename (binary serialization) _daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan))!; // Do not rename (binary serialization) diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.TransitionTime.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.TransitionTime.cs index 53808118d47cab..5b8cca7450b2f9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.TransitionTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.TransitionTime.cs @@ -127,8 +127,10 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("TimeOfDay", _timeOfDay); // Do not rename (binary serialization) info.AddValue("Month", _month); // Do not rename (binary serialization) info.AddValue("Week", _week); // Do not rename (binary serialization) @@ -137,8 +139,10 @@ void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext cont info.AddValue("IsFixedDateRule", _isFixedDateRule); // Do not rename (binary serialization) } - private TransitionTime(SerializationInfo info!!, StreamingContext context) + private TransitionTime(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime))!; // Do not rename (binary serialization) _month = (byte)info.GetValue("Month", typeof(byte))!; // Do not rename (binary serialization) _week = (byte)info.GetValue("Week", typeof(byte))!; // Do not rename (binary serialization) diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs index 391f39e1693a8f..ad3cc1e2148d93 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs @@ -320,8 +320,10 @@ private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATI /// This function will either return a valid TimeZoneInfo instance or /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'. /// - public static TimeZoneInfo FindSystemTimeZoneById(string id!!) + public static TimeZoneInfo FindSystemTimeZoneById(string id) { + ArgumentNullException.ThrowIfNull(id); + // Special case for Utc to avoid having TryGetTimeZone creating a new Utc object if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs index 80a256c99cf56f..236442359f0113 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs @@ -582,8 +582,10 @@ public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string s /// /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone /// - public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone!!) + public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) { + ArgumentNullException.ThrowIfNull(destinationTimeZone); + // calculate the destination time zone offset DateTime utcDateTime = dateTimeOffset.UtcDateTime; TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone); @@ -600,8 +602,10 @@ public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZone /// /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone /// - public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone!!) + public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) { + ArgumentNullException.ThrowIfNull(destinationTimeZone); + // Special case to give a way clearing the cache without exposing ClearCachedData() if (dateTime.Ticks == 0) { @@ -624,8 +628,11 @@ public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZon internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) => ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData); - private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone!!, TimeZoneInfo destinationTimeZone!!, TimeZoneInfoOptions flags, CachedData cachedData) + private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) { + ArgumentNullException.ThrowIfNull(sourceTimeZone); + ArgumentNullException.ThrowIfNull(destinationTimeZone); + DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone); if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind)) { @@ -737,8 +744,10 @@ public bool Equals([NotNullWhen(true)] TimeZoneInfo? other) => public override bool Equals([NotNullWhen(true)] object? obj) => Equals(obj as TimeZoneInfo); - public static TimeZoneInfo FromSerializedString(string source!!) + public static TimeZoneInfo FromSerializedString(string source) { + ArgumentNullException.ThrowIfNull(source); + if (source.Length == 0) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source)); @@ -795,8 +804,10 @@ public static ReadOnlyCollection GetSystemTimeZones() /// /// Value equality on the "adjustmentRules" array /// - public bool HasSameRules(TimeZoneInfo other!!) + public bool HasSameRules(TimeZoneInfo other) { + ArgumentNullException.ThrowIfNull(other); + // check the utcOffset and supportsDaylightSavingTime members if (_baseUtcOffset != other._baseUtcOffset || _supportsDaylightSavingTime != other._supportsDaylightSavingTime) @@ -990,8 +1001,10 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("Id", _id); // Do not rename (binary serialization) info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization) info.AddValue("StandardName", _standardDisplayName); // Do not rename (binary serialization) @@ -1001,8 +1014,10 @@ void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext cont info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization) } - private TimeZoneInfo(SerializationInfo info!!, StreamingContext context) + private TimeZoneInfo(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + _id = (string)info.GetValue("Id", typeof(string))!; // Do not rename (binary serialization) _displayName = (string?)info.GetValue("DisplayName", typeof(string)); // Do not rename (binary serialization) _standardDisplayName = (string?)info.GetValue("StandardName", typeof(string)); // Do not rename (binary serialization) diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs index e088eae799c6ae..59fe5a34a93054 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs @@ -17,8 +17,10 @@ namespace System // public abstract partial class Type { - public virtual bool IsEnumDefined(object value!!) + public virtual bool IsEnumDefined(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value)); @@ -61,8 +63,10 @@ public virtual bool IsEnumDefined(object value!!) } } - public virtual string? GetEnumName(object value!!) + public virtual string? GetEnumName(object value) { + ArgumentNullException.ThrowIfNull(value); + if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs index 966818949dc257..3990964dabc821 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs @@ -115,8 +115,10 @@ public bool IsVisible } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] - public virtual Type[] FindInterfaces(TypeFilter filter!!, object? filterCriteria) + public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) { + ArgumentNullException.ThrowIfNull(filter); + Type?[] c = GetInterfaces(); int cnt = 0; for (int i = 0; i < c.Length; i++) diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index cf1b6e32f480a2..4907875d591c5e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -157,8 +157,10 @@ public ConstructorInfo? TypeInitializer public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] - public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types!!, ParameterModifier[]? modifiers) + public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { + ArgumentNullException.ThrowIfNull(types); + for (int i = 0; i < types.Length; i++) { ArgumentNullException.ThrowIfNull(types[i], nameof(types)); @@ -236,8 +238,10 @@ public ConstructorInfo? TypeInitializer [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "This is finding the MemberInfo with the same MetadataToken as specified MemberInfo. If the specified MemberInfo " + "exists and wasn't trimmed, then the current Type's MemberInfo couldn't have been trimmed.")] - public virtual MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member!!) + public virtual MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; foreach (MemberInfo myMemberInfo in GetMembers(all)) { @@ -260,8 +264,10 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public MethodInfo? GetMethod(string name) => GetMethod(name, Type.DefaultLookup); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - public MethodInfo? GetMethod(string name!!, BindingFlags bindingAttr) + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(name); + return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null); } @@ -293,8 +299,11 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - public MethodInfo? GetMethod(string name!!, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types!!, ParameterModifier[]? modifiers) + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(types); + for (int i = 0; i < types.Length; i++) { ArgumentNullException.ThrowIfNull(types[i], nameof(types)); @@ -315,8 +324,10 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - public MethodInfo? GetMethod(string name!!, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) + public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { + ArgumentNullException.ThrowIfNull(name); + if (genericParameterCount < 0) throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(genericParameterCount)); ArgumentNullException.ThrowIfNull(types); @@ -352,16 +363,20 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public PropertyInfo? GetProperty(string name) => GetProperty(name, Type.DefaultLookup); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - public PropertyInfo? GetProperty(string name!!, BindingFlags bindingAttr) + public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(name); + return GetPropertyImpl(name, bindingAttr, null, null, null, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "Linker doesn't recognize GetPropertyImpl(BindingFlags.Public) but this is what the body is doing")] - public PropertyInfo? GetProperty(string name!!, Type? returnType) + public PropertyInfo? GetProperty(string name, Type? returnType) { + ArgumentNullException.ThrowIfNull(name); + return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null); } @@ -375,8 +390,11 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types, ParameterModifier[]? modifiers) => GetProperty(name, Type.DefaultLookup, null, returnType, types, modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - public PropertyInfo? GetProperty(string name!!, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types!!, ParameterModifier[]? modifiers) + public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(types); + return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers); } @@ -399,13 +417,17 @@ private protected static ArgumentException CreateGetMemberWithSameMetadataDefini public virtual MemberInfo[] GetDefaultMembers() => throw NotImplemented.ByDesign; public virtual RuntimeTypeHandle TypeHandle => throw new NotSupportedException(); - public static RuntimeTypeHandle GetTypeHandle(object o!!) + public static RuntimeTypeHandle GetTypeHandle(object o) { + ArgumentNullException.ThrowIfNull(o); + return o.GetType().TypeHandle; } - public static Type[] GetTypeArray(object[] args!!) + public static Type[] GetTypeArray(object[] args) { + ArgumentNullException.ThrowIfNull(args); + Type[] cls = new Type[args.Length]; for (int i = 0; i < cls.Length; i++) { diff --git a/src/libraries/System.Private.CoreLib/src/System/TypedReference.cs b/src/libraries/System.Private.CoreLib/src/System/TypedReference.cs index c1bc05498276dd..ca25fe9e924c7c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TypedReference.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TypedReference.cs @@ -13,8 +13,11 @@ namespace System public ref partial struct TypedReference { - public static TypedReference MakeTypedReference(object target!!, FieldInfo[] flds!!) + public static TypedReference MakeTypedReference(object target, FieldInfo[] flds) { + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(flds); + if (flds.Length == 0) throw new ArgumentException(SR.Arg_ArrayZeroError, nameof(flds)); diff --git a/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs b/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs index 715e00dfb1d231..81d2f3956b749a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs @@ -72,8 +72,10 @@ private unsafe UIntPtr(SerializationInfo info, StreamingContext context) _value = (void*)l; } - void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("value", ToUInt64()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs b/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs index 897db7e0e735c4..792cfe4e74f60c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs @@ -31,9 +31,11 @@ internal static void GetUnitySerializationInfo(SerializationInfo info, int unity } #pragma warning disable CA2229 // public for compat - public UnitySerializationHolder(SerializationInfo info!!, StreamingContext context) + public UnitySerializationHolder(SerializationInfo info, StreamingContext context) #pragma warning restore CA2229 { + ArgumentNullException.ThrowIfNull(info); + // We are ignoring any other serialization input as we are only concerned about DBNull. // We also store data and use it for erorr logging. _unityType = info.GetInt32("UnityType"); diff --git a/src/libraries/System.Private.CoreLib/src/System/Version.cs b/src/libraries/System.Private.CoreLib/src/System/Version.cs index 96da170cc6dd7a..50551dc3e398d5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Version.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Version.cs @@ -263,8 +263,10 @@ bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, Re _Revision == -1 ? 3 : 4; - public static Version Parse(string input!!) + public static Version Parse(string input) { + ArgumentNullException.ThrowIfNull(input); + return ParseVersion(input.AsSpan(), throwOnFailure: true)!; } diff --git a/src/libraries/System.Private.CoreLib/src/System/WeakReference.T.cs b/src/libraries/System.Private.CoreLib/src/System/WeakReference.T.cs index a1517385593936..3e48b74ae5c8e1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/WeakReference.T.cs +++ b/src/libraries/System.Private.CoreLib/src/System/WeakReference.T.cs @@ -30,8 +30,10 @@ public WeakReference(T target, bool trackResurrection) Create(target, trackResurrection); } - private WeakReference(SerializationInfo info!!, StreamingContext context) + private WeakReference(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + T target = (T)info.GetValue("TrackedObject", typeof(T))!; // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) @@ -54,8 +56,10 @@ public bool TryGetTarget([MaybeNullWhen(false), NotNullWhen(true)] out T target) return o != null; } - public void GetObjectData(SerializationInfo info!!, StreamingContext context) + public void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("TrackedObject", this.Target, typeof(T)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", IsTrackResurrection()); // Do not rename (binary serialization) } diff --git a/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs b/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs index 759ef6d6f87821..c05af0c1ee558b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs +++ b/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs @@ -24,16 +24,20 @@ public WeakReference(object? target, bool trackResurrection) Create(target, trackResurrection); } - protected WeakReference(SerializationInfo info!!, StreamingContext context) + protected WeakReference(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + object? target = info.GetValue("TrackedObject", typeof(object)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) Create(target, trackResurrection); } - public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(info); + info.AddValue("TrackedObject", Target, typeof(object)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", IsTrackResurrection()); // Do not rename (binary serialization) } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs index 33283d2cc46e65..de5354b6e72aa0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs @@ -104,7 +104,7 @@ public DataContractSerializer(Type type, DataContractSerializerSettings? setting } [MemberNotNull(nameof(_rootType))] - private void Initialize(Type type!!, + private void Initialize(Type type, IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, @@ -112,6 +112,8 @@ private void Initialize(Type type!!, DataContractResolver? dataContractResolver, bool serializeReadOnlyTypes) { + ArgumentNullException.ThrowIfNull(type); + _rootType = type; if (knownTypes != null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 600377f74eb814..51588fc4256ddd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -32,8 +32,10 @@ internal DataContractSet(IDataContractSurrogate dataContractSurrogate, ICollecti #endif [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal DataContractSet(DataContractSet dataContractSet!!) + internal DataContractSet(DataContractSet dataContractSet) { + ArgumentNullException.ThrowIfNull(dataContractSet); + //this.dataContractSurrogate = dataContractSet.dataContractSurrogate; _referencedTypes = dataContractSet._referencedTypes; _referencedCollectionTypes = dataContractSet._referencedCollectionTypes; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs index a7390ae70ef835..a9c7be7e873fa4 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs @@ -212,8 +212,10 @@ public override bool IsStartObject(XmlDictionaryReader reader) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public override object? ReadObject(Stream stream!!) + public override object? ReadObject(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)); } @@ -256,8 +258,10 @@ public override void WriteEndObject(XmlDictionaryWriter writer) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public override void WriteObject(Stream stream!!, object? graph) + public override void WriteObject(Stream stream, object? graph) { + ArgumentNullException.ThrowIfNull(stream); + XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, false); // ownsStream WriteObject(jsonWriter, graph); jsonWriter.Flush(); @@ -519,7 +523,7 @@ private void AddCollectionItemTypeToKnownTypes(Type knownType) [MemberNotNull(nameof(_rootType))] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private void Initialize(Type type!!, + private void Initialize(Type type, IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, @@ -528,6 +532,8 @@ private void Initialize(Type type!!, DateTimeFormat? dateTimeFormat, bool useSimpleDictionaryFormat) { + ArgumentNullException.ThrowIfNull(type); + _rootType = type; if (knownTypes != null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs index 3d85ac6c55303b..713697934b987d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DateTimeFormat.cs @@ -32,8 +32,11 @@ public DateTimeFormat(string formatString) : this(formatString, DateTimeFormatIn /// /// Specifies the formatString to be used. /// Specifies the formatProvider to be used. - public DateTimeFormat(string formatString!!, IFormatProvider formatProvider!!) + public DateTimeFormat(string formatString, IFormatProvider formatProvider) { + ArgumentNullException.ThrowIfNull(formatString); + ArgumentNullException.ThrowIfNull(formatProvider); + _formatString = formatString; _formatProvider = formatProvider; _dateTimeStyles = DateTimeStyles.RoundtripKind; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs index c27cac95fbe2c3..5e3ca3318d68df 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs @@ -19,8 +19,10 @@ public static XmlDictionaryReader CreateJsonReader(Stream stream, XmlDictionaryR return CreateJsonReader(stream, null, quotas, null); } - public static XmlDictionaryReader CreateJsonReader(byte[] buffer!!, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateJsonReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(buffer); + return CreateJsonReader(buffer, 0, buffer.Length, null, quotas, null); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs index 35280dd78abebe..b7edc56ac412bc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs @@ -799,9 +799,11 @@ public override int ReadValueChunk(char[] chars, int offset, int count) return base.ReadValueChunk(chars, offset, count); } - public void SetInput(byte[] buffer!!, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative); @@ -826,9 +828,11 @@ public void SetInput(byte[] buffer!!, int offset, int count, Encoding? encoding, ResetState(); } - public void SetInput(Stream stream!!, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { + ArgumentNullException.ThrowIfNull(stream); + MoveToInitial(quotas, onClose); stream = new JsonEncodingStreamWrapper(stream, encoding, true); @@ -843,8 +847,10 @@ public override void StartCanonicalization(Stream stream, bool includeComments, throw new NotSupportedException(); } - internal static void CheckArray(Array array!!, int offset, int count) + internal static void CheckArray(Array array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs index 86b1d98b0632f2..e1301e39f33d9a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs @@ -228,8 +228,10 @@ public override void Flush() _nodeWriter.Flush(); } - public override string? LookupPrefix(string ns!!) + public override string? LookupPrefix(string ns) { + ArgumentNullException.ThrowIfNull(ns); + if (ns == Globals.XmlnsNamespace) { return Globals.XmlnsPrefix; @@ -245,8 +247,11 @@ public override void Flush() return null; } - public void SetOutput(Stream stream!!, Encoding encoding!!, bool ownsStream) + public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(encoding); + if (encoding.WebName != Encoding.UTF8.WebName) { stream = new JsonEncodingStreamWrapper(stream, encoding, false); @@ -364,8 +369,10 @@ public override void WriteArray(string? prefix, XmlDictionaryString localName, X throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteBase64(byte[] buffer!!, int index, int count) + public override void WriteBase64(byte[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -385,8 +392,10 @@ public override void WriteBase64(byte[] buffer!!, int index, int count) _nodeWriter.WriteBase64Text(buffer, 0, buffer, index, count); } - public override void WriteBinHex(byte[] buffer!!, int index, int count) + public override void WriteBinHex(byte[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -416,8 +425,10 @@ public override void WriteCharEntity(char ch) WriteString(ch.ToString()); } - public override void WriteChars(char[] buffer!!, int index, int count) + public override void WriteChars(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -693,8 +704,10 @@ public override void WriteProcessingInstruction(string name, string? text) } } - public override void WriteQualifiedName(string localName!!, string? ns) + public override void WriteQualifiedName(string localName, string? ns) { + ArgumentNullException.ThrowIfNull(localName); + if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); @@ -712,8 +725,10 @@ public override void WriteRaw(string data) WriteString(data); } - public override void WriteRaw(char[] buffer!!, int index, int count) + public override void WriteRaw(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -857,8 +872,10 @@ public override void WriteStartDocument() } } - public override void WriteStartElement(string? prefix, string localName!!, string? ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { + ArgumentNullException.ThrowIfNull(localName); + if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); @@ -1050,14 +1067,18 @@ public override void WriteValue(TimeSpan value) _nodeWriter.WriteTimeSpanText(value); } - public override void WriteValue(UniqueId value!!) + public override void WriteValue(UniqueId value) { + ArgumentNullException.ThrowIfNull(value); + StartText(); _nodeWriter.WriteUniqueIdText(value); } - public override void WriteValue(object value!!) + public override void WriteValue(object value) { + ArgumentNullException.ThrowIfNull(value); + if (IsClosed) { ThrowClosed(); @@ -1402,8 +1423,10 @@ private void WriteJsonQuote() _nodeWriter.WriteText(JsonGlobals.QuoteChar); } - private void WritePrimitiveValue(object value!!) + private void WritePrimitiveValue(object value) { + ArgumentNullException.ThrowIfNull(value); + if (IsClosed) { ThrowClosed(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs index 977a25f8f7bc5e..364038c247a3e2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs @@ -26,8 +26,11 @@ public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pa // Here you can provide your own root element Xpath which will replace the Xpath of the top level element [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public static string CreateFromDataContractSerializer(Type type!!, MemberInfo[] pathToMember!!, StringBuilder? rootElementXpath, out XmlNamespaceManager namespaces) + public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder? rootElementXpath, out XmlNamespaceManager namespaces) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(pathToMember); + DataContract currentContract = DataContract.GetDataContract(type); ExportContext context; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index 1398b7d1368159..5d1cc609678b91 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -24,34 +24,44 @@ public abstract class XmlObjectSerializer public abstract void WriteEndObject(XmlDictionaryWriter writer); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual void WriteObject(Stream stream!!, object? graph) + public virtual void WriteObject(Stream stream, object? graph) { + ArgumentNullException.ThrowIfNull(stream); + XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/); WriteObject(writer, graph); writer.Flush(); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual void WriteObject(XmlWriter writer!!, object? graph) + public virtual void WriteObject(XmlWriter writer, object? graph) { + ArgumentNullException.ThrowIfNull(writer); + WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual void WriteStartObject(XmlWriter writer!!, object? graph) + public virtual void WriteStartObject(XmlWriter writer, object? graph) { + ArgumentNullException.ThrowIfNull(writer); + WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual void WriteObjectContent(XmlWriter writer!!, object? graph) + public virtual void WriteObjectContent(XmlWriter writer, object? graph) { + ArgumentNullException.ThrowIfNull(writer); + WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual void WriteEndObject(XmlWriter writer!!) + public virtual void WriteEndObject(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } @@ -68,8 +78,10 @@ internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? gra } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal void WriteObjectHandleExceptions(XmlWriterDelegator writer!!, object? graph, DataContractResolver? dataContractResolver) + internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver) { + ArgumentNullException.ThrowIfNull(writer); + try { InternalWriteObject(writer, graph, dataContractResolver); @@ -127,8 +139,10 @@ internal virtual void InternalWriteEndObject(XmlWriterDelegator writer) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer!!, object? graph) + internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object? graph) { + ArgumentNullException.ThrowIfNull(writer); + try { InternalWriteStartObject(writer, graph); @@ -144,8 +158,10 @@ internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer!!, obje } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer!!, object? graph) + internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object? graph) { + ArgumentNullException.ThrowIfNull(writer); + try { if (writer.WriteState != WriteState.Element) @@ -163,8 +179,10 @@ internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer!!, ob } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer!!) + internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer) { + ArgumentNullException.ThrowIfNull(writer); + try { InternalWriteEndObject(writer); @@ -226,14 +244,18 @@ internal static bool IsContractDeclared(DataContract contract, DataContract decl } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual object? ReadObject(Stream stream!!) + public virtual object? ReadObject(Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual object? ReadObject(XmlReader reader!!) + public virtual object? ReadObject(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } @@ -244,8 +266,10 @@ internal static bool IsContractDeclared(DataContract contract, DataContract decl } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual object? ReadObject(XmlReader reader!!, bool verifyObjectName) + public virtual object? ReadObject(XmlReader reader, bool verifyObjectName) { + ArgumentNullException.ThrowIfNull(reader); + return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName); } @@ -253,8 +277,10 @@ internal static bool IsContractDeclared(DataContract contract, DataContract decl public abstract object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName); [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public virtual bool IsStartObject(XmlReader reader!!) + public virtual bool IsStartObject(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + return IsStartObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } @@ -287,8 +313,10 @@ internal virtual bool InternalIsStartObject(XmlReaderDelegator reader) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader!!, bool verifyObjectName, DataContractResolver? dataContractResolver) + internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver? dataContractResolver) { + ArgumentNullException.ThrowIfNull(reader); + try { return InternalReadObject(reader, verifyObjectName, dataContractResolver); @@ -304,8 +332,10 @@ internal virtual bool InternalIsStartObject(XmlReaderDelegator reader) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader!!) + internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader) { + ArgumentNullException.ThrowIfNull(reader); + try { return InternalIsStartObject(reader); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs index 54d9cd0fa2d56c..15cc14c4c6a666 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs @@ -15,8 +15,10 @@ internal class XmlReaderDelegator protected XmlDictionaryReader? dictionaryReader; protected bool isEndOfEmptyElement; - public XmlReaderDelegator(XmlReader reader!!) + public XmlReaderDelegator(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + this.reader = reader; this.dictionaryReader = reader as XmlDictionaryReader; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs index 1dfe131a5ca34f..059d42eca693cb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs @@ -9,8 +9,10 @@ namespace System.Runtime.Serialization public static class XmlSerializableServices { - public static XmlNode[] ReadNodes(XmlReader xmlReader!!) + public static XmlNode[] ReadNodes(XmlReader xmlReader) { + ArgumentNullException.ThrowIfNull(xmlReader); + XmlDocument doc = new XmlDocument(); List nodeList = new List(); if (xmlReader.MoveToFirstAttribute()) @@ -50,8 +52,10 @@ private static bool IsValidAttribute(XmlReader xmlReader) xmlReader.LocalName != "xmlns"; } - public static void WriteNodes(XmlWriter xmlWriter!!, XmlNode?[]? nodes) + public static void WriteNodes(XmlWriter xmlWriter, XmlNode?[]? nodes) { + ArgumentNullException.ThrowIfNull(xmlWriter); + if (nodes != null) for (int i = 0; i < nodes.Length; i++) if (nodes[i] != null) @@ -59,8 +63,11 @@ public static void WriteNodes(XmlWriter xmlWriter!!, XmlNode?[]? nodes) } internal static string AddDefaultSchemaMethodName = "AddDefaultSchema"; - public static void AddDefaultSchema(XmlSchemaSet schemas!!, XmlQualifiedName typeQName!!) + public static void AddDefaultSchema(XmlSchemaSet schemas, XmlQualifiedName typeQName) { + ArgumentNullException.ThrowIfNull(schemas); + ArgumentNullException.ThrowIfNull(typeQName); + SchemaExporter.AddDefaultXmlType(schemas, typeQName.Name, typeQName.Namespace); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs index c18286bd6c5bcc..b9441eec91778c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs @@ -14,8 +14,10 @@ internal class XmlWriterDelegator internal int depth; private int _prefixes; - public XmlWriterDelegator(XmlWriter writer!!) + public XmlWriterDelegator(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + this.writer = writer; this.dictionaryWriter = writer as XmlDictionaryWriter; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs index cb5b347f35d961..ad147ba1af8fd7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs @@ -62,8 +62,10 @@ private static DataContractSet DataContractSet } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public void Export(ICollection assemblies!!) + public void Export(ICollection assemblies) { + ArgumentNullException.ThrowIfNull(assemblies); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -87,8 +89,10 @@ public void Export(ICollection assemblies!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public void Export(ICollection types!!) + public void Export(ICollection types) { + ArgumentNullException.ThrowIfNull(types); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -109,8 +113,10 @@ public void Export(ICollection types!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public void Export(Type type!!) + public void Export(Type type) { + ArgumentNullException.ThrowIfNull(type); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -125,8 +131,10 @@ public void Export(Type type!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public XmlQualifiedName GetSchemaTypeName(Type type!!) + public XmlQualifiedName GetSchemaTypeName(Type type) { + ArgumentNullException.ThrowIfNull(type); + type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); @@ -137,8 +145,10 @@ public XmlQualifiedName GetSchemaTypeName(Type type!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public XmlSchemaType? GetSchemaType(Type type!!) + public XmlSchemaType? GetSchemaType(Type type) { + ArgumentNullException.ThrowIfNull(type); + type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); @@ -149,8 +159,10 @@ public XmlQualifiedName GetSchemaTypeName(Type type!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public XmlQualifiedName? GetRootElementName(Type type!!) + public XmlQualifiedName? GetRootElementName(Type type) { + ArgumentNullException.ThrowIfNull(type); + type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); @@ -217,8 +229,10 @@ private void AddKnownTypes() } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public bool CanExport(ICollection assemblies!!) + public bool CanExport(ICollection assemblies) { + ArgumentNullException.ThrowIfNull(assemblies); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -247,8 +261,10 @@ public bool CanExport(ICollection assemblies!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public bool CanExport(ICollection types!!) + public bool CanExport(ICollection types) { + ArgumentNullException.ThrowIfNull(types); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -274,8 +290,10 @@ public bool CanExport(ICollection types!!) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public bool CanExport(Type type!!) + public bool CanExport(Type type) { + ArgumentNullException.ThrowIfNull(type); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs index 8cac5e6aa23076..50b7fa46280a6a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs @@ -53,8 +53,10 @@ private static bool IsValidTailBytes(int v3, int v4) return !(v3 == 64 && v4 != 64); } - public unsafe override int GetByteCount(char[] chars!!, int index, int count) + public unsafe override int GetByteCount(char[] chars, int index, int count) { + ArgumentNullException.ThrowIfNull(chars); + if (index < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative)); if (index > chars.Length) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs index bf27460e9f7478..d09c801cafa2f0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs @@ -62,8 +62,10 @@ public UniqueId(byte[] guid) : this(guid, 0) { } - public unsafe UniqueId(byte[] guid!!, int offset) + public unsafe UniqueId(byte[] guid, int offset) { + ArgumentNullException.ThrowIfNull(guid); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > guid.Length) @@ -77,8 +79,10 @@ public unsafe UniqueId(byte[] guid!!, int offset) } } - public unsafe UniqueId(string value!!) + public unsafe UniqueId(string value) { + ArgumentNullException.ThrowIfNull(value); + if (value.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.XmlInvalidUniqueId)); fixed (char* pch = value) @@ -88,8 +92,10 @@ public unsafe UniqueId(string value!!) _s = value; } - public unsafe UniqueId(char[] chars!!, int offset, int count) + public unsafe UniqueId(char[] chars, int offset, int count) { + ArgumentNullException.ThrowIfNull(chars); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > chars.Length) @@ -192,8 +198,10 @@ private unsafe void UnsafeParse(char* chars, int charCount) } } - public int ToCharArray(char[] chars!!, int offset) + public int ToCharArray(char[] chars, int offset) { + ArgumentNullException.ThrowIfNull(chars); + int count = CharArrayLength; if (offset < 0) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index aabb0c693ce9cb..1b9dffa71635e6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -130,8 +130,10 @@ protected void MoveToNode(XmlNode node) _value = null; } - protected void MoveToInitial(XmlDictionaryReaderQuotas quotas!!) + protected void MoveToInitial(XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(quotas); + quotas.InternalCopyTo(_quotas); _quotas.MakeReadOnly(); _nsMgr.Clear(); @@ -539,8 +541,10 @@ private XmlAttributeNode GetAttributeNode(int index) return _attributeNodes![index]; } - private XmlAttributeNode? GetAttributeNode(string name!!) + private XmlAttributeNode? GetAttributeNode(string name) { + ArgumentNullException.ThrowIfNull(name); + if (!_node.CanGetAttribute) return null; int index = name.IndexOf(':'); @@ -585,8 +589,10 @@ private XmlAttributeNode GetAttributeNode(int index) return null; } - private XmlAttributeNode? GetAttributeNode(string localName!!, string? namespaceUri) + private XmlAttributeNode? GetAttributeNode(string localName, string? namespaceUri) { + ArgumentNullException.ThrowIfNull(localName); + if (namespaceUri == null) namespaceUri = string.Empty; if (!_node.CanGetAttribute) @@ -610,8 +616,10 @@ private XmlAttributeNode GetAttributeNode(int index) return null; } - private XmlAttributeNode? GetAttributeNode(XmlDictionaryString localName!!, XmlDictionaryString namespaceUri) + private XmlAttributeNode? GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { + ArgumentNullException.ThrowIfNull(localName); + if (namespaceUri == null) namespaceUri = XmlDictionaryString.Empty; if (!_node.CanGetAttribute) @@ -980,22 +988,30 @@ public override string Prefix } - public override bool IsLocalName(string localName!!) + public override bool IsLocalName(string localName) { + ArgumentNullException.ThrowIfNull(localName); + return _node.IsLocalName(localName); } - public override bool IsLocalName(XmlDictionaryString localName!!) + public override bool IsLocalName(XmlDictionaryString localName) { + ArgumentNullException.ThrowIfNull(localName); + return _node.IsLocalName(localName); } - public override bool IsNamespaceUri(string namespaceUri!!) + public override bool IsNamespaceUri(string namespaceUri) { + ArgumentNullException.ThrowIfNull(namespaceUri); + return _node.IsNamespaceUri(namespaceUri); } - public override bool IsNamespaceUri(XmlDictionaryString namespaceUri!!) + public override bool IsNamespaceUri(XmlDictionaryString namespaceUri) { + ArgumentNullException.ThrowIfNull(namespaceUri); + return _node.IsNamespaceUri(namespaceUri); } public override sealed bool IsStartElement() @@ -1043,13 +1059,19 @@ public override bool IsStartElement(string localName, string namespaceUri) return (_node.NodeType == XmlNodeType.Element || IsStartElement()) && _node.LocalName == localName && _node.IsNamespaceUri(namespaceUri); } - public override bool IsStartElement(XmlDictionaryString localName!!, XmlDictionaryString namespaceUri!!) + public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { + ArgumentNullException.ThrowIfNull(localName); + ArgumentNullException.ThrowIfNull(namespaceUri); + return (_node.NodeType == XmlNodeType.Element || IsStartElement()) && _node.LocalName == localName && _node.IsNamespaceUri(namespaceUri); } - public override int IndexOfLocalName(string[] localNames!!, string namespaceUri!!) + public override int IndexOfLocalName(string[] localNames, string namespaceUri) { + ArgumentNullException.ThrowIfNull(localNames); + ArgumentNullException.ThrowIfNull(namespaceUri); + QNameType qnameType = _node.QNameType; if (_node.IsNamespaceUri(namespaceUri)) { @@ -1086,8 +1108,11 @@ public override int IndexOfLocalName(string[] localNames!!, string namespaceUri! return -1; } - public override int IndexOfLocalName(XmlDictionaryString[] localNames!!, XmlDictionaryString namespaceUri!!) + public override int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri) { + ArgumentNullException.ThrowIfNull(localNames); + ArgumentNullException.ThrowIfNull(namespaceUri); + QNameType qnameType = _node.QNameType; if (_node.IsNamespaceUri(namespaceUri)) { @@ -1124,8 +1149,10 @@ public override int IndexOfLocalName(XmlDictionaryString[] localNames!!, XmlDict return -1; } - public override int ReadValueChunk(char[] chars!!, int offset, int count) + public override int ReadValueChunk(char[] chars, int offset, int count) { + ArgumentNullException.ThrowIfNull(chars); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > chars.Length) @@ -1152,8 +1179,10 @@ public override int ReadValueChunk(char[] chars!!, int offset, int count) return actual; } - public override int ReadValueAsBase64(byte[] buffer!!, int offset, int count) + public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > buffer.Length) @@ -1310,8 +1339,10 @@ public override int ReadElementContentAsBase64(byte[] buffer, int offset, int co return i; } - public override int ReadContentAsBase64(byte[] buffer!!, int offset, int count) + public override int ReadContentAsBase64(byte[] buffer, int offset, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > buffer.Length) @@ -1346,8 +1377,10 @@ public override byte[] ReadContentAsBinHex() return ReadContentAsBinHex(_quotas.MaxArrayLength); } - public override int ReadContentAsBinHex(byte[] buffer!!, int offset, int count) + public override int ReadContentAsBinHex(byte[] buffer, int offset, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > buffer.Length) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index 4e29c32ed3f1e4..8ae28963eb92a5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -815,8 +815,10 @@ private Task EndStartElementAsync() return _writer.WriteEndStartElementAsync(false); } - public override string? LookupPrefix(string ns!!) + public override string? LookupPrefix(string ns) { + ArgumentNullException.ThrowIfNull(ns); + if (IsClosed) ThrowClosed(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs index 581bb07c8fde6e..9b6911441951b2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs @@ -34,12 +34,14 @@ public XmlBinaryReader() { } - public void SetInput(byte[] buffer!!, int offset, int count, + public void SetInput(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > buffer.Length) @@ -53,12 +55,14 @@ public void SetInput(byte[] buffer!!, int offset, int count, _buffered = true; } - public void SetInput(Stream stream!!, + public void SetInput(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { + ArgumentNullException.ThrowIfNull(stream); + MoveToInitial(quotas, session, null); BufferReader.SetBuffer(stream, dictionary, session); _buffered = false; @@ -1209,8 +1213,10 @@ private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString nam return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType && !Signing; } - private static void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > array.Length) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs index 550f6a87fb96c5..5f8a48710c7cdf 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs @@ -70,8 +70,10 @@ public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? resu return false; } - public bool TryLookup(string value!!, [NotNullWhen(true)] out XmlDictionaryString? result) + public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { + ArgumentNullException.ThrowIfNull(value); + if (_strings != null) { for (int i = 0; i < _strings.Length; i++) @@ -101,8 +103,10 @@ public bool TryLookup(string value!!, [NotNullWhen(true)] out XmlDictionaryStrin return false; } - public bool TryLookup(XmlDictionaryString value!!, [NotNullWhen(true)] out XmlDictionaryString? result) + public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { + ArgumentNullException.ThrowIfNull(value); + if (value.Dictionary != this) { result = null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs index a6fb4a559ddb70..d9c6458c95061e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs @@ -1075,8 +1075,10 @@ internal sealed class XmlBinaryWriter : XmlBaseWriter, IXmlBinaryWriterInitializ private byte[]? _bytes; - public void SetOutput(Stream stream!!, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream) + public void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream) { + ArgumentNullException.ThrowIfNull(stream); + if (_writer == null) _writer = new XmlBinaryNodeWriter(); _writer.SetOutput(stream, dictionary, session, ownsStream); @@ -1202,8 +1204,10 @@ private unsafe void UnsafeWriteArray(string? prefix, XmlDictionaryString localNa // WriteEndArray(); } - private static void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > array.Length) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs index a622ce29a3edb3..cfdaacd2d66e37 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs @@ -25,8 +25,10 @@ public XmlBinaryWriterSession() _strings = new PriorityDictionary(); } - public virtual bool TryAdd(XmlDictionaryString value!!, out int key) + public virtual bool TryAdd(XmlDictionaryString value, out int key) { + ArgumentNullException.ThrowIfNull(value); + IntArray? keys; if (_maps.TryGetValue(value.Dictionary, out keys)) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index f4b0d7b45dd270..7af5afb76abfdf 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -54,8 +54,10 @@ public XmlCanonicalWriter() { } - public void SetOutput(Stream stream!!, bool includeComments, string[]? inclusivePrefixes) + public void SetOutput(Stream stream, bool includeComments, string[]? inclusivePrefixes) { + ArgumentNullException.ThrowIfNull(stream); + if (_writer == null) { _writer = new XmlUTF8NodeWriter(s_isEscapedAttributeChar, s_isEscapedElementChar); @@ -141,8 +143,10 @@ public static void WriteDeclaration() { } - public void WriteComment(string value!!) + public void WriteComment(string value) { + ArgumentNullException.ThrowIfNull(value); + ThrowIfClosed(); if (_includeComments) { @@ -178,8 +182,11 @@ private void EndElement() _xmlnsOffset = _scopes[_depth].xmlnsOffset; } - public void WriteStartElement(string prefix!!, string localName!!) + public void WriteStartElement(string prefix, string localName) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(localName); + ThrowIfClosed(); bool isRootElement = (_depth == 0); @@ -336,8 +343,11 @@ public void WriteEndStartElement(bool isEmpty) _elementBuffer = null; } - public void WriteEndElement(string prefix!!, string localName!!) + public void WriteEndElement(string prefix, string localName) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(localName); + ThrowIfClosed(); _writer.WriteEndElement(prefix, localName); EndElement(); @@ -359,8 +369,11 @@ private void EnsureXmlnsBuffer(int byteCount) } [MemberNotNull(nameof(_xmlnsAttributes))] - public void WriteXmlnsAttribute(string prefix!!, string ns!!) + public void WriteXmlnsAttribute(string prefix, string ns) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(ns); + ThrowIfClosed(); if (prefix.Length > int.MaxValue - ns.Length) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(ns), SR.Format(SR.CombinedPrefixNSLength, int.MaxValue / maxBytesPerChar))); @@ -418,8 +431,11 @@ public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefi AddXmlnsAttribute(ref xmlnsAttribute); } - public void WriteStartAttribute(string prefix!!, string localName!!) + public void WriteStartAttribute(string prefix, string localName) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(localName); + ThrowIfClosed(); _attribute.offset = _elementWriter.Position; _attribute.length = 0; @@ -487,8 +503,10 @@ public void WriteCharEntity(int ch) } } - public void WriteEscapedText(string value!!) + public void WriteEscapedText(string value) { + ArgumentNullException.ThrowIfNull(value); + ThrowIfClosed(); // Skip all white spaces before the start of root element. if (_depth > 0) @@ -504,8 +522,10 @@ public void WriteEscapedText(string value!!) } } - public void WriteEscapedText(byte[] chars!!, int offset, int count) + public void WriteEscapedText(byte[] chars, int offset, int count) { + ArgumentNullException.ThrowIfNull(chars); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > chars.Length) @@ -581,8 +601,10 @@ public void WriteText(byte[] chars, int offset, int count) } } - public void WriteText(string value!!) + public void WriteText(string value) { + ArgumentNullException.ThrowIfNull(value); + if (value.Length > 0) { if (_inStartElement) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs index 34c000a5087215..869d2bc240d72b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs @@ -84,8 +84,10 @@ public virtual bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryStri return true; } - public virtual bool TryLookup(XmlDictionaryString value!!, [NotNullWhen(true)] out XmlDictionaryString? result) + public virtual bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { + ArgumentNullException.ThrowIfNull(value); + if (value.Dictionary != this) { result = null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs index 8a8a5d123560dd..e2daea3d7425a0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs @@ -19,8 +19,10 @@ public abstract class XmlDictionaryReader : XmlReader { internal const int MaxInitialArrayLength = 65535; - public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader!!) + public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; if (dictionaryReader == null) @@ -31,8 +33,10 @@ public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader!!) return dictionaryReader; } - public static XmlDictionaryReader CreateBinaryReader(byte[] buffer!!, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(buffer); + return CreateBinaryReader(buffer, 0, buffer.Length, quotas); } @@ -88,8 +92,10 @@ public static XmlDictionaryReader CreateBinaryReader(Stream stream, return reader; } - public static XmlDictionaryReader CreateTextReader(byte[] buffer!!, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(buffer); + return CreateTextReader(buffer, 0, buffer.Length, quotas); } @@ -122,8 +128,10 @@ public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding? enco return reader; } - public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding!!, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(encoding); + return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas); } @@ -143,8 +151,10 @@ public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] enc throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } - public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding!!, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(encoding); + return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas); } @@ -219,18 +229,24 @@ public virtual bool IsLocalName(string localName) return this.LocalName == localName; } - public virtual bool IsLocalName(XmlDictionaryString localName!!) + public virtual bool IsLocalName(XmlDictionaryString localName) { + ArgumentNullException.ThrowIfNull(localName); + return IsLocalName(localName.Value); } - public virtual bool IsNamespaceUri(string namespaceUri!!) + public virtual bool IsNamespaceUri(string namespaceUri) { + ArgumentNullException.ThrowIfNull(namespaceUri); + return this.NamespaceURI == namespaceUri; } - public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri!!) + public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri) { + ArgumentNullException.ThrowIfNull(namespaceUri); + return IsNamespaceUri(namespaceUri.Value); } @@ -277,8 +293,11 @@ public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryS return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } - public virtual int IndexOfLocalName(string[] localNames!!, string namespaceUri!!) + public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { + ArgumentNullException.ThrowIfNull(localNames); + ArgumentNullException.ThrowIfNull(namespaceUri); + if (this.NamespaceURI == namespaceUri) { string localName = this.LocalName; @@ -297,8 +316,11 @@ public virtual int IndexOfLocalName(string[] localNames!!, string namespaceUri!! return -1; } - public virtual int IndexOfLocalName(XmlDictionaryString[] localNames!!, XmlDictionaryString namespaceUri!!) + public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri) { + ArgumentNullException.ThrowIfNull(localNames); + ArgumentNullException.ThrowIfNull(namespaceUri); + if (this.NamespaceURI == namespaceUri.Value) { string localName = this.LocalName; @@ -588,8 +610,10 @@ public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespace return base.ReadContentAs(type, namespaceResolver); } - public virtual string ReadContentAsString(string[] strings!!, out int index) + public virtual string ReadContentAsString(string[] strings, out int index) { + ArgumentNullException.ThrowIfNull(strings); + string s = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) @@ -606,8 +630,10 @@ public virtual string ReadContentAsString(string[] strings!!, out int index) return s; } - public virtual string ReadContentAsString(XmlDictionaryString[] strings!!, out int index) + public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index) { + ArgumentNullException.ThrowIfNull(strings); + string s = ReadContentAsString(); index = -1; for (int i = 0; i < strings.Length; i++) @@ -980,8 +1006,10 @@ public virtual bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDic return false; } - private static void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > array.Length) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs index 5f3736d7fc821a..7d451ecbba9271 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReaderQuotas.cs @@ -62,8 +62,10 @@ public static XmlDictionaryReaderQuotas Max } } - public void CopyTo(XmlDictionaryReaderQuotas quotas!!) + public void CopyTo(XmlDictionaryReaderQuotas quotas) { + ArgumentNullException.ThrowIfNull(quotas); + if (quotas._readOnly) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.QuotaCopyReadOnly)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs index 1738a49a5b448d..97b285f2680ea9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs @@ -21,8 +21,11 @@ public class XmlDictionaryString private byte[]? _buffer; private static readonly EmptyStringDictionary s_emptyStringDictionary = new EmptyStringDictionary(); - public XmlDictionaryString(IXmlDictionary dictionary!!, string value!!, int key) + public XmlDictionaryString(IXmlDictionary dictionary, string value, int key) { + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentNullException.ThrowIfNull(value); + if (key < MinKey || key > MaxKey) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(key), SR.Format(SR.ValueMustBeInRange, MinKey, MaxKey))); _dictionary = dictionary; @@ -99,8 +102,10 @@ public XmlDictionaryString EmptyString } } - public bool TryLookup(string value!!, [NotNullWhen(true)] out XmlDictionaryString? result) + public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { + ArgumentNullException.ThrowIfNull(value); + if (value.Length == 0) { result = _empty; @@ -121,8 +126,10 @@ public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? resu return false; } - public bool TryLookup(XmlDictionaryString value!!, [NotNullWhen(true)] out XmlDictionaryString? result) + public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { + ArgumentNullException.ThrowIfNull(value); + if (value.Dictionary != this) { result = null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs index 1ba3975e8b9b6b..49babc9f9f167e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs @@ -68,8 +68,10 @@ public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encod throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } - public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer!!) + public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter; if (dictionaryWriter == null) @@ -111,8 +113,10 @@ public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryStr WriteAttributeString((string?)null, localName, namespaceUri, value); } - public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri!!) + public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri) { + ArgumentNullException.ThrowIfNull(namespaceUri); + if (prefix == null) { if (LookupPrefix(namespaceUri) != null) @@ -161,8 +165,10 @@ public virtual void WriteString(XmlDictionaryString? value) WriteString(XmlDictionaryString.GetString(value)); } - public virtual void WriteQualifiedName(XmlDictionaryString localName!!, XmlDictionaryString? namespaceUri) + public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { + ArgumentNullException.ThrowIfNull(localName); + if (namespaceUri == null) namespaceUri = XmlDictionaryString.Empty; #pragma warning suppress 56506 // Microsoft, XmlDictionaryString.Empty is never null @@ -175,8 +181,10 @@ public virtual void WriteValue(XmlDictionaryString? value) } - public virtual void WriteValue(UniqueId value!!) + public virtual void WriteValue(UniqueId value) { + ArgumentNullException.ThrowIfNull(value); + WriteString(value.ToString()); } @@ -190,8 +198,10 @@ public virtual void WriteValue(TimeSpan value) WriteString(XmlConvert.ToString(value)); } - public virtual void WriteValue(IStreamProvider value!!) + public virtual void WriteValue(IStreamProvider value) { + ArgumentNullException.ThrowIfNull(value); + Stream stream = value.GetStream(); if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.XmlInvalidStream)); @@ -381,8 +391,10 @@ public override void WriteNode(XmlReader reader, bool defattr) base.WriteNode(reader, defattr); } - public virtual void WriteNode(XmlDictionaryReader reader!!, bool defattr) + public virtual void WriteNode(XmlDictionaryReader reader, bool defattr) { + ArgumentNullException.ThrowIfNull(reader); + int d = (reader.NodeType == XmlNodeType.None ? -1 : reader.Depth); do { @@ -432,8 +444,10 @@ public virtual void WriteNode(XmlDictionaryReader reader!!, bool defattr) while (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)); } - private static void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > array.Length) @@ -833,8 +847,10 @@ public override void WriteValue(long value) _writer.WriteValue(value); } - public override void WriteXmlnsAttribute(string? prefix, string namespaceUri!!) + public override void WriteXmlnsAttribute(string? prefix, string namespaceUri) { + ArgumentNullException.ThrowIfNull(namespaceUri); + if (prefix == null) { if (LookupPrefix(namespaceUri) != null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs index 2bcad0e51e3f30..578117e87fb6ed 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs @@ -553,8 +553,10 @@ public XmlUTF8TextReader() _localName = new StringHandle(BufferReader); } - public void SetInput(byte[] buffer!!, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) + public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); if (offset > buffer.Length) @@ -569,8 +571,10 @@ public void SetInput(byte[] buffer!!, int offset, int count, Encoding? encoding, _buffered = true; } - public void SetInput(Stream stream!!, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) + public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { + ArgumentNullException.ThrowIfNull(stream); + MoveToInitial(quotas, onClose); stream = new EncodingStreamWrapper(stream, encoding); BufferReader.SetBuffer(stream, null, null); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs index 484bfc0b07dbbf..5de6dd8b6785ea 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs @@ -16,8 +16,11 @@ internal sealed class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializ { private XmlUTF8NodeWriter? _writer; - public void SetOutput(Stream stream!!, Encoding encoding!!, bool ownsStream) + public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(encoding); + if (encoding.WebName != Encoding.UTF8.WebName) { stream = new EncodingStreamWrapper(stream, encoding, true); diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs index 77614b4f7b3b1a..3801f21c3cd321 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs @@ -301,8 +301,10 @@ public static string ObjectToStringRef(ref object o) return o.ToString() ?? string.Empty; } - public static double GetDateValueRef(ref object dtv!!) + public static double GetDateValueRef(ref object dtv) { + ArgumentNullException.ThrowIfNull(dtv); + if (!(dtv is DateTime dt)) throw new InvalidCastException(SR.Format(SR.UnableCastObjectToType, dtv.GetType(), typeof(DateTime))); if (dt.Kind == DateTimeKind.Local) diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index b50015c8144657..481522023fd942 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -362,8 +362,10 @@ private void EnsureHostString(bool allowDnsOptimization) // a user, or that was copied & pasted from a document. That is, we do not // expect already encoded URI to be supplied. // - public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString!!) + public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString) { + ArgumentNullException.ThrowIfNull(uriString); + CreateThis(uriString, false, UriKind.Absolute); DebugSetLeftCtor(); } @@ -374,8 +376,10 @@ public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString!!) // Uri constructor. Assumes that input string is canonically escaped // [Obsolete("This constructor has been deprecated; the dontEscape parameter is always false. Use Uri(string) instead.")] - public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString!!, bool dontEscape) + public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString, bool dontEscape) { + ArgumentNullException.ThrowIfNull(uriString); + CreateThis(uriString, dontEscape, UriKind.Absolute); DebugSetLeftCtor(); } @@ -387,8 +391,10 @@ public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString!!, bool do // DontEscape is true // [Obsolete("This constructor has been deprecated; the dontEscape parameter is always false. Use Uri(Uri, string) instead.")] - public Uri(Uri baseUri!!, string? relativeUri, bool dontEscape) + public Uri(Uri baseUri, string? relativeUri, bool dontEscape) { + ArgumentNullException.ThrowIfNull(baseUri); + if (!baseUri.IsAbsoluteUri) throw new ArgumentOutOfRangeException(nameof(baseUri)); @@ -399,8 +405,10 @@ public Uri(Uri baseUri!!, string? relativeUri, bool dontEscape) // // Uri(string, UriKind); // - public Uri([StringSyntax(StringSyntaxAttribute.Uri, "uriKind")] string uriString!!, UriKind uriKind) + public Uri([StringSyntax(StringSyntaxAttribute.Uri, "uriKind")] string uriString, UriKind uriKind) { + ArgumentNullException.ThrowIfNull(uriString); + CreateThis(uriString, false, uriKind); DebugSetLeftCtor(); } @@ -410,8 +418,10 @@ public Uri([StringSyntax(StringSyntaxAttribute.Uri, "uriKind")] string uriString /// /// A string that identifies the resource to be represented by the instance. /// Options that control how the is created and behaves. - public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString!!, in UriCreationOptions creationOptions) + public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString, in UriCreationOptions creationOptions) { + ArgumentNullException.ThrowIfNull(uriString); + CreateThis(uriString, false, UriKind.Absolute, in creationOptions); DebugSetLeftCtor(); } @@ -423,8 +433,10 @@ public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString!!, in UriC // also be an absolute URI, in which case the resultant URI is constructed // entirely from it // - public Uri(Uri baseUri!!, string? relativeUri) + public Uri(Uri baseUri, string? relativeUri) { + ArgumentNullException.ThrowIfNull(baseUri); + if (!baseUri.IsAbsoluteUri) throw new ArgumentOutOfRangeException(nameof(baseUri)); @@ -522,8 +534,10 @@ private void CreateUri(Uri baseUri, string? relativeUri, bool dontEscape) // Uri(Uri , Uri ) // Note: a static Create() method should be used by users, not this .ctor // - public Uri(Uri baseUri!!, Uri relativeUri) + public Uri(Uri baseUri, Uri relativeUri) { + ArgumentNullException.ThrowIfNull(baseUri); + if (!baseUri.IsAbsoluteUri) throw new ArgumentOutOfRangeException(nameof(baseUri)); @@ -1753,8 +1767,10 @@ public override bool Equals([NotNullWhen(true)] object? comparand) return string.Equals(selfUrl, otherUrl, IsUncOrDosPath ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } - public Uri MakeRelativeUri(Uri uri!!) + public Uri MakeRelativeUri(Uri uri) { + ArgumentNullException.ThrowIfNull(uri); + if (IsNotAbsoluteUri || uri.IsNotAbsoluteUri) throw new InvalidOperationException(SR.net_uri_NotAbsolute); @@ -5104,8 +5120,10 @@ private static string PathDifference(string path1, string path2, bool compareCas // ArgumentNullException, InvalidOperationException // [Obsolete("Uri.MakeRelative has been deprecated. Use MakeRelativeUri(Uri uri) instead.")] - public string MakeRelative(Uri toUri!!) + public string MakeRelative(Uri toUri) { + ArgumentNullException.ThrowIfNull(toUri); + if (IsNotAbsoluteUri || toUri.IsNotAbsoluteUri) throw new InvalidOperationException(SR.net_uri_NotAbsolute); diff --git a/src/libraries/System.Private.Uri/src/System/UriBuilder.cs b/src/libraries/System.Private.Uri/src/System/UriBuilder.cs index ba7d39dc9a4acc..29611f4f5f9db1 100644 --- a/src/libraries/System.Private.Uri/src/System/UriBuilder.cs +++ b/src/libraries/System.Private.Uri/src/System/UriBuilder.cs @@ -38,8 +38,10 @@ public UriBuilder([StringSyntax(StringSyntaxAttribute.Uri)] string uri) SetFieldsFromUri(); } - public UriBuilder(Uri uri!!) + public UriBuilder(Uri uri) { + ArgumentNullException.ThrowIfNull(uri); + _uri = uri; SetFieldsFromUri(); } diff --git a/src/libraries/System.Private.Uri/src/System/UriExt.cs b/src/libraries/System.Private.Uri/src/System/UriExt.cs index 71168fb4243dd7..aaa93e2e7f2f1f 100644 --- a/src/libraries/System.Private.Uri/src/System/UriExt.cs +++ b/src/libraries/System.Private.Uri/src/System/UriExt.cs @@ -554,8 +554,10 @@ internal unsafe bool InternalIsWellFormedOriginalString() return true; } - public static string UnescapeDataString(string stringToUnescape!!) + public static string UnescapeDataString(string stringToUnescape) { + ArgumentNullException.ThrowIfNull(stringToUnescape); + if (stringToUnescape.Length == 0) return string.Empty; @@ -852,8 +854,10 @@ internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFo } } - public bool IsBaseOf(Uri uri!!) + public bool IsBaseOf(Uri uri) { + ArgumentNullException.ThrowIfNull(uri); + if (!IsAbsoluteUri) return false; diff --git a/src/libraries/System.Private.Uri/src/System/UriHelper.cs b/src/libraries/System.Private.Uri/src/System/UriHelper.cs index ead1ed38c90f77..b7d4335b848ebe 100644 --- a/src/libraries/System.Private.Uri/src/System/UriHelper.cs +++ b/src/libraries/System.Private.Uri/src/System/UriHelper.cs @@ -107,9 +107,11 @@ internal static unsafe bool TestForSubPath(char* selfPtr, int selfLength, char* } internal static string EscapeString( - string stringToEscape!!, // same name as public API + string stringToEscape, // same name as public API bool checkExistingEscaped, ReadOnlySpan unreserved, char forceEscape1 = '\0', char forceEscape2 = '\0') { + ArgumentNullException.ThrowIfNull(stringToEscape); + if (stringToEscape.Length == 0) { return string.Empty; diff --git a/src/libraries/System.Private.Uri/src/System/UriScheme.cs b/src/libraries/System.Private.Uri/src/System/UriScheme.cs index ce2d1015140553..f9bcc7ab120df7 100644 --- a/src/libraries/System.Private.Uri/src/System/UriScheme.cs +++ b/src/libraries/System.Private.Uri/src/System/UriScheme.cs @@ -163,8 +163,11 @@ protected virtual bool IsWellFormedOriginalString(Uri uri) // // Registers a custom Uri parser based on a scheme string // - public static void Register(UriParser uriParser!!, string schemeName!!, int defaultPort) + public static void Register(UriParser uriParser, string schemeName, int defaultPort) { + ArgumentNullException.ThrowIfNull(uriParser); + ArgumentNullException.ThrowIfNull(schemeName); + if (schemeName.Length == 1) throw new ArgumentOutOfRangeException(nameof(schemeName)); @@ -181,8 +184,10 @@ public static void Register(UriParser uriParser!!, string schemeName!!, int defa // // Is a Uri scheme known to System.Uri? // - public static bool IsKnownScheme(string schemeName!!) + public static bool IsKnownScheme(string schemeName) { + ArgumentNullException.ThrowIfNull(schemeName); + if (!Uri.CheckSchemeName(schemeName)) throw new ArgumentOutOfRangeException(nameof(schemeName)); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs index f3c86d6ea74905..e255b0e1afbf36 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/Extensions.cs @@ -21,8 +21,10 @@ public static class Extensions /// Attributes for every in the target /// of . /// - public static IEnumerable Attributes(this IEnumerable source!!) + public static IEnumerable Attributes(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return GetAttributes(source, null); } @@ -36,8 +38,10 @@ public static IEnumerable Attributes(this IEnumerable sou /// Attributes with a matching for every in /// the target of . /// - public static IEnumerable Attributes(this IEnumerable source!!, XName? name) + public static IEnumerable Attributes(this IEnumerable source, XName? name) { + ArgumentNullException.ThrowIfNull(source); + return name != null ? GetAttributes(source, name) : XAttribute.EmptySequence; } @@ -51,8 +55,10 @@ public static IEnumerable Attributes(this IEnumerable sou /// and it's parent up to the root) of each of the s in this /// of . /// - public static IEnumerable Ancestors(this IEnumerable source!!) where T : XNode + public static IEnumerable Ancestors(this IEnumerable source) where T : XNode { + ArgumentNullException.ThrowIfNull(source); + return GetAncestors(source, null, false); } @@ -66,8 +72,10 @@ public static IEnumerable Ancestors(this IEnumerable source!!) /// and it's parent up to the root) that have a matching . This is done for each /// in this of . /// - public static IEnumerable Ancestors(this IEnumerable source!!, XName? name) where T : XNode + public static IEnumerable Ancestors(this IEnumerable source, XName? name) where T : XNode { + ArgumentNullException.ThrowIfNull(source); + return name != null ? GetAncestors(source, name, false) : XElement.EmptySequence; } @@ -83,8 +91,10 @@ public static IEnumerable Ancestors(this IEnumerable source!!, /// This is done for each in this of /// . /// - public static IEnumerable AncestorsAndSelf(this IEnumerable source!!) + public static IEnumerable AncestorsAndSelf(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return GetAncestors(source, null, true); } @@ -100,16 +110,20 @@ public static IEnumerable AncestorsAndSelf(this IEnumerable /// that match the passed in . This is done for each /// in this of . /// - public static IEnumerable AncestorsAndSelf(this IEnumerable source!!, XName? name) + public static IEnumerable AncestorsAndSelf(this IEnumerable source, XName? name) { + ArgumentNullException.ThrowIfNull(source); + return name != null ? GetAncestors(source, name, true) : XElement.EmptySequence; } /// /// Returns an of over the content of a set of nodes /// - public static IEnumerable Nodes(this IEnumerable source!!) where T : XContainer + public static IEnumerable Nodes(this IEnumerable source) where T : XContainer { + ArgumentNullException.ThrowIfNull(source); + return NodesIterator(source); } @@ -135,8 +149,10 @@ private static IEnumerable NodesIterator(IEnumerable source) where /// /// Returns an of over the descendants of a set of nodes /// - public static IEnumerable DescendantNodes(this IEnumerable source!!) where T : XContainer + public static IEnumerable DescendantNodes(this IEnumerable source) where T : XContainer { + ArgumentNullException.ThrowIfNull(source); + return GetDescendantNodes(source, false); } @@ -150,8 +166,10 @@ public static IEnumerable DescendantNodes(this IEnumerable source! /// and their children down to the leaf level). This is done for each in /// this of . /// - public static IEnumerable Descendants(this IEnumerable source!!) where T : XContainer + public static IEnumerable Descendants(this IEnumerable source) where T : XContainer { + ArgumentNullException.ThrowIfNull(source); + return GetDescendants(source, null, false); } @@ -165,8 +183,10 @@ public static IEnumerable Descendants(this IEnumerable source!! /// and their children down to the leaf level) that have a matching . This is done /// for each in this of . /// - public static IEnumerable Descendants(this IEnumerable source!!, XName? name) where T : XContainer + public static IEnumerable Descendants(this IEnumerable source, XName? name) where T : XContainer { + ArgumentNullException.ThrowIfNull(source); + return name != null ? GetDescendants(source, name, false) : XElement.EmptySequence; } @@ -182,8 +202,10 @@ public static IEnumerable Descendants(this IEnumerable source!! /// This is done for each /// in this of . /// - public static IEnumerable DescendantNodesAndSelf(this IEnumerable source!!) + public static IEnumerable DescendantNodesAndSelf(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return GetDescendantNodes(source, true); } @@ -199,8 +221,10 @@ public static IEnumerable DescendantNodesAndSelf(this IEnumerable in this /// of . /// - public static IEnumerable DescendantsAndSelf(this IEnumerable source!!) + public static IEnumerable DescendantsAndSelf(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return GetDescendants(source, null, true); } @@ -216,8 +240,10 @@ public static IEnumerable DescendantsAndSelf(this IEnumerable. This is done for /// each in this of . /// - public static IEnumerable DescendantsAndSelf(this IEnumerable source!!, XName? name) + public static IEnumerable DescendantsAndSelf(this IEnumerable source, XName? name) { + ArgumentNullException.ThrowIfNull(source); + return name != null ? GetDescendants(source, name, true) : XElement.EmptySequence; } @@ -229,8 +255,10 @@ public static IEnumerable DescendantsAndSelf(this IEnumerable of containing the child elements /// for each in this of . /// - public static IEnumerable Elements(this IEnumerable source!!) where T : XContainer + public static IEnumerable Elements(this IEnumerable source) where T : XContainer { + ArgumentNullException.ThrowIfNull(source); + return GetElements(source, null); } @@ -242,8 +270,10 @@ public static IEnumerable Elements(this IEnumerable source!!) w /// An of containing the child elements /// for each in this of . /// - public static IEnumerable Elements(this IEnumerable source!!, XName? name) where T : XContainer + public static IEnumerable Elements(this IEnumerable source, XName? name) where T : XContainer { + ArgumentNullException.ThrowIfNull(source); + return name != null ? GetElements(source, name) : XElement.EmptySequence; } @@ -256,8 +286,10 @@ public static IEnumerable Elements(this IEnumerable source!!, X /// for each in this of . /// in document order /// - public static IEnumerable InDocumentOrder(this IEnumerable source!!) where T : XNode? + public static IEnumerable InDocumentOrder(this IEnumerable source) where T : XNode? { + ArgumentNullException.ThrowIfNull(source); + return DocumentOrderIterator(source); } @@ -277,8 +309,10 @@ private static IEnumerable DocumentOrderIterator(IEnumerable source) wh /// . Note that this method uses snapshot semantics (copies the /// attributes to an array before deleting each). /// - public static void Remove(this IEnumerable source!!) + public static void Remove(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + int count; XAttribute?[] attributes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) @@ -293,8 +327,10 @@ public static void Remove(this IEnumerable source!!) /// T which must be a derived from . Note that this method uses snapshot semantics /// (copies the s to an array before deleting each). /// - public static void Remove(this IEnumerable source!!) where T : XNode + public static void Remove(this IEnumerable source) where T : XNode { + ArgumentNullException.ThrowIfNull(source); + int count; T?[] nodes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs index 25d8a8f90d0b6d..721d6c7ce66256 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs @@ -51,8 +51,11 @@ public static IEnumerable EmptySequence /// /// Thrown if the passed in name or value are null. /// - public XAttribute(XName name!!, object value!!) + public XAttribute(XName name, object value) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + string s = XContainer.GetStringValue(value); ValidateAttribute(name, s); this.name = name; @@ -67,8 +70,10 @@ public XAttribute(XName name!!, object value!!) /// /// Thrown if the specified is null. /// - public XAttribute(XAttribute other!!) + public XAttribute(XAttribute other) { + ArgumentNullException.ThrowIfNull(other); + name = other.name; value = other.value; } @@ -191,8 +196,10 @@ public void Remove() /// /// Thrown if the specified value is null. /// - public void SetValue(object value!!) + public void SetValue(object value) { + ArgumentNullException.ThrowIfNull(value); + Value = XContainer.GetStringValue(value); } @@ -244,8 +251,10 @@ public override string ToString() /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator bool(XAttribute attribute!!) + public static explicit operator bool(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); } @@ -279,8 +288,10 @@ public static explicit operator bool(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator int(XAttribute attribute!!) + public static explicit operator int(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToInt32(attribute.value); } @@ -314,8 +325,10 @@ public static explicit operator int(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator uint(XAttribute attribute!!) + public static explicit operator uint(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToUInt32(attribute.value); } @@ -349,8 +362,10 @@ public static explicit operator uint(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator long(XAttribute attribute!!) + public static explicit operator long(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToInt64(attribute.value); } @@ -384,8 +399,10 @@ public static explicit operator long(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator ulong(XAttribute attribute!!) + public static explicit operator ulong(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToUInt64(attribute.value); } @@ -419,8 +436,10 @@ public static explicit operator ulong(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator float(XAttribute attribute!!) + public static explicit operator float(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToSingle(attribute.value); } @@ -454,8 +473,10 @@ public static explicit operator float(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator double(XAttribute attribute!!) + public static explicit operator double(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToDouble(attribute.value); } @@ -489,8 +510,10 @@ public static explicit operator double(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator decimal(XAttribute attribute!!) + public static explicit operator decimal(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToDecimal(attribute.value); } @@ -524,8 +547,10 @@ public static explicit operator decimal(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator DateTime(XAttribute attribute!!) + public static explicit operator DateTime(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); } @@ -559,8 +584,10 @@ public static explicit operator DateTime(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator DateTimeOffset(XAttribute attribute!!) + public static explicit operator DateTimeOffset(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToDateTimeOffset(attribute.value); } @@ -594,8 +621,10 @@ public static explicit operator DateTimeOffset(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator TimeSpan(XAttribute attribute!!) + public static explicit operator TimeSpan(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToTimeSpan(attribute.value); } @@ -629,8 +658,10 @@ public static explicit operator TimeSpan(XAttribute attribute!!) /// Thrown if the specified attribute is null. /// [CLSCompliant(false)] - public static explicit operator Guid(XAttribute attribute!!) + public static explicit operator Guid(XAttribute attribute) { + ArgumentNullException.ThrowIfNull(attribute); + return XmlConvert.ToGuid(attribute.value); } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XCData.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XCData.cs index 1110a474ac29e3..8ba336fa4320a7 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XCData.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XCData.cs @@ -45,8 +45,10 @@ public override XmlNodeType NodeType /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteCData(text); } @@ -62,8 +64,10 @@ public override void WriteTo(XmlWriter writer!!) /// /// A Task that represents the eventual completion of the operation. /// - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return writer.WriteCDataAsync(text); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs index 4e8adaf36a1640..d23cbfe5aff7e9 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs @@ -26,8 +26,10 @@ public class XComment : XNode /// /// Thrown if the specified value is null. /// - public XComment(string value!!) + public XComment(string value) { + ArgumentNullException.ThrowIfNull(value); + this.value = value; } @@ -35,8 +37,10 @@ public XComment(string value!!) /// Initializes a new comment node from an existing comment node. /// /// Comment node to copy from. - public XComment(XComment other!!) + public XComment(XComment other) { + ArgumentNullException.ThrowIfNull(other); + this.value = other.value; } @@ -87,8 +91,10 @@ public string Value /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteComment(value); } @@ -99,8 +105,10 @@ public override void WriteTo(XmlWriter writer!!) /// The to write this to. /// /// A cancellation token. - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return writer.WriteCommentAsync(value); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs index 49c782a3245fe1..c5c6047a09202c 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs @@ -26,8 +26,10 @@ public abstract class XContainer : XNode internal XContainer() { } - internal XContainer(XContainer other!!) + internal XContainer(XContainer other) { + ArgumentNullException.ThrowIfNull(other); + if (other.content is string) { this.content = other.content; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs index 52c1f5ce5d04d2..38953f4ed05c6c 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs @@ -48,8 +48,10 @@ public XDeclaration(string? version, string? encoding, string? standalone) /// /// The used to initialize this object. /// - public XDeclaration(XDeclaration other!!) + public XDeclaration(XDeclaration other) { + ArgumentNullException.ThrowIfNull(other); + _version = other._version; _encoding = other._encoding; _standalone = other._standalone; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs index 17c06fc4461c85..e08773353462f7 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs @@ -419,8 +419,10 @@ public static XDocument Load(XmlReader reader) /// A new containing the contents of the passed /// in . /// - public static XDocument Load(XmlReader reader!!, LoadOptions options) + public static XDocument Load(XmlReader reader, LoadOptions options) { + ArgumentNullException.ThrowIfNull(reader); + if (reader.ReadState == ReadState.Initial) reader.Read(); XDocument d = InitLoad(reader, options); @@ -449,8 +451,10 @@ public static XDocument Load(XmlReader reader!!, LoadOptions options) /// A new containing the contents of the passed /// in . /// - public static Task LoadAsync(XmlReader reader!!, LoadOptions options, CancellationToken cancellationToken) + public static Task LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(reader); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return LoadAsyncInternal(reader, options, cancellationToken); @@ -789,8 +793,10 @@ public void Save(string fileName, SaveOptions options) /// The to output the content of this /// . /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + if (_declaration != null && _declaration.Standalone == "yes") { writer.WriteStartDocument(true); @@ -817,8 +823,10 @@ public override void WriteTo(XmlWriter writer!!) /// . /// /// A cancellation token. - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return WriteToAsyncInternal(writer, cancellationToken); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs index 3b422190e91e3c..adab1ef756accc 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs @@ -33,8 +33,10 @@ public XDocumentType(string name, string? publicId, string? systemId, string? in /// from another XDocumentType object. /// /// object to copy from. - public XDocumentType(XDocumentType other!!) + public XDocumentType(XDocumentType other) { + ArgumentNullException.ThrowIfNull(other); + _name = other._name; _publicId = other._publicId; _systemId = other._systemId; @@ -139,8 +141,10 @@ public string? SystemId /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteDocType(_name, _publicId, _systemId, _internalSubset); } @@ -153,8 +157,10 @@ public override void WriteTo(XmlWriter writer!!) /// /// A cancellation token. /// - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return writer.WriteDocTypeAsync(_name, _publicId, _systemId, _internalSubset); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs index 7638a52bc3c85f..bee393c0b8b028 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs @@ -56,8 +56,10 @@ public static IEnumerable EmptySequence /// /// The name of the element. /// - public XElement(XName name!!) + public XElement(XName name) { + ArgumentNullException.ThrowIfNull(name); + this.name = name; } @@ -124,8 +126,10 @@ public XElement(XElement other) /// The object whose value will be used /// to initialize the new element. /// - public XElement(XStreamingElement other!!) + public XElement(XStreamingElement other) { + ArgumentNullException.ThrowIfNull(other); + name = other.name; AddContentSkipNotify(other.content); } @@ -489,8 +493,10 @@ public XNamespace GetDefaultNamespace() /// /// The for which to get a prefix /// The namespace prefix string - public string? GetPrefixOfNamespace(XNamespace ns!!) + public string? GetPrefixOfNamespace(XNamespace ns) { + ArgumentNullException.ThrowIfNull(ns); + string namespaceName = ns.NamespaceName; bool hasInScopeNamespace = false; XElement? e = this; @@ -799,8 +805,10 @@ public static XElement Load(XmlReader reader) /// A new containing the contents of the passed /// in . /// - public static XElement Load(XmlReader reader!!, LoadOptions options) + public static XElement Load(XmlReader reader, LoadOptions options) { + ArgumentNullException.ThrowIfNull(reader); + if (reader.MoveToContent() != XmlNodeType.Element) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ExpectedNodeType, XmlNodeType.Element, reader.NodeType)); XElement e = new XElement(reader, options); reader.MoveToContent(); @@ -825,8 +833,10 @@ public static XElement Load(XmlReader reader!!, LoadOptions options) /// A new containing the contents of the passed /// in . /// - public static Task LoadAsync(XmlReader reader!!, LoadOptions options, CancellationToken cancellationToken) + public static Task LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(reader); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return LoadAsyncInternal(reader, options, cancellationToken); @@ -1149,8 +1159,10 @@ public async Task SaveAsync(TextWriter textWriter, SaveOptions options, Cancella /// /// The to output the XML to. /// - public void Save(XmlWriter writer!!) + public void Save(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteStartDocument(); WriteTo(writer); writer.WriteEndDocument(); @@ -1163,8 +1175,10 @@ public void Save(XmlWriter writer!!) /// The to output the XML to. /// /// A cancellation token. - public Task SaveAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public Task SaveAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return SaveAsyncInternal(writer, cancellationToken); @@ -1272,8 +1286,10 @@ public void SetElementValue(XName name, object? value) /// /// Thrown if the specified value is null. /// - public void SetValue(object value!!) + public void SetValue(object value) { + ArgumentNullException.ThrowIfNull(value); + Value = GetStringValue(value); } @@ -1283,8 +1299,10 @@ public void SetValue(object value!!) /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + new ElementWriter(writer).WriteElement(this); } @@ -1295,8 +1313,10 @@ public override void WriteTo(XmlWriter writer!!) /// The to write this to. /// /// A cancellation token. - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return new ElementWriter(writer).WriteElementAsync(this, cancellationToken); @@ -1341,8 +1361,10 @@ public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancella /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator bool(XElement element!!) + public static explicit operator bool(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToBoolean(element.Value.ToLowerInvariant()); } @@ -1382,8 +1404,10 @@ public static explicit operator bool(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator int(XElement element!!) + public static explicit operator int(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToInt32(element.Value); } @@ -1423,8 +1447,10 @@ public static explicit operator int(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator uint(XElement element!!) + public static explicit operator uint(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToUInt32(element.Value); } @@ -1464,8 +1490,10 @@ public static explicit operator uint(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator long(XElement element!!) + public static explicit operator long(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToInt64(element.Value); } @@ -1505,8 +1533,10 @@ public static explicit operator long(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator ulong(XElement element!!) + public static explicit operator ulong(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToUInt64(element.Value); } @@ -1546,8 +1576,10 @@ public static explicit operator ulong(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator float(XElement element!!) + public static explicit operator float(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToSingle(element.Value); } @@ -1587,8 +1619,10 @@ public static explicit operator float(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator double(XElement element!!) + public static explicit operator double(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToDouble(element.Value); } @@ -1628,8 +1662,10 @@ public static explicit operator double(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator decimal(XElement element!!) + public static explicit operator decimal(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToDecimal(element.Value); } @@ -1669,8 +1705,10 @@ public static explicit operator decimal(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator DateTime(XElement element!!) + public static explicit operator DateTime(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return DateTime.Parse(element.Value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); } @@ -1710,8 +1748,10 @@ public static explicit operator DateTime(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator DateTimeOffset(XElement element!!) + public static explicit operator DateTimeOffset(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToDateTimeOffset(element.Value); } @@ -1751,8 +1791,10 @@ public static explicit operator DateTimeOffset(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator TimeSpan(XElement element!!) + public static explicit operator TimeSpan(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToTimeSpan(element.Value); } @@ -1792,8 +1834,10 @@ public static explicit operator TimeSpan(XElement element!!) /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator Guid(XElement element!!) + public static explicit operator Guid(XElement element) { + ArgumentNullException.ThrowIfNull(element); + return XmlConvert.ToGuid(element.Value); } @@ -1832,8 +1876,10 @@ public static explicit operator Guid(XElement element!!) /// The stream from which the /// is deserialized. /// - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + if (parent != null || annotations != null || content != null || lastAttr != null) throw new InvalidOperationException(SR.InvalidOperation_DeserializeInstance); if (reader.MoveToContent() != XmlNodeType.Element) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ExpectedNodeType, XmlNodeType.Element, reader.NodeType)); ReadElementFrom(reader, LoadOptions.None); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs index 903b5942bd40b5..5d280dd6a5ac2f 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs @@ -53,8 +53,10 @@ public string NamespaceName /// The returned object is guaranteed to be atomic (i.e. the only one in the system for this /// particular expanded name). /// - public XName GetName(string localName!!) + public XName GetName(string localName) { + ArgumentNullException.ThrowIfNull(localName); + return GetName(localName, 0, localName.Length); } @@ -111,8 +113,10 @@ public static XNamespace Xmlns /// The returned object is guaranteed to be atomic /// (i.e. the only one in the system for that particular namespace name). /// - public static XNamespace Get(string namespaceName!!) + public static XNamespace Get(string namespaceName) { + ArgumentNullException.ThrowIfNull(namespaceName); + return Get(namespaceName, 0, namespaceName.Length); } @@ -134,8 +138,10 @@ public static XNamespace Get(string namespaceName!!) /// The namespace for the expanded name. /// The local name for the expanded name. /// The new XName constructed from the namespace and local name. - public static XName operator +(XNamespace ns!!, string localName) + public static XName operator +(XNamespace ns, string localName) { + ArgumentNullException.ThrowIfNull(ns); + return ns.GetName(localName); } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs index 5c22fa17b53cd9..5e642531dd1ce8 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs @@ -438,8 +438,10 @@ public bool IsBefore(XNode? node) /// /// Thrown if the is not positioned on a recognized node type. /// - public static XNode ReadFrom(XmlReader reader!!) + public static XNode ReadFrom(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + if (reader.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); switch (reader.NodeType) { @@ -474,8 +476,10 @@ public static XNode ReadFrom(XmlReader reader!!) /// /// Thrown if the is not positioned on a recognized node type. /// - public static Task ReadFromAsync(XmlReader reader!!, CancellationToken cancellationToken) + public static Task ReadFromAsync(XmlReader reader, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(reader); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return ReadFromAsyncInternal(reader, cancellationToken); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs index 38f7ddda288733..055d2ed9c15c7a 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs @@ -77,8 +77,10 @@ public XElement? Parent /// Adds an object to the annotation list of this . /// /// The annotation to add. - public void AddAnnotation(object annotation!!) + public void AddAnnotation(object annotation) { + ArgumentNullException.ThrowIfNull(annotation); + if (annotations == null) { annotations = annotation is object[]? new object[] { annotation } : annotation; @@ -113,8 +115,10 @@ public void AddAnnotation(object annotation!!) /// The first matching annotation object, or null /// if no annotation is the specified type. /// - public object? Annotation(Type type!!) + public object? Annotation(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (annotations != null) { object?[]? a = annotations as object[]; @@ -191,8 +195,10 @@ public void AddAnnotation(object annotation!!) /// /// The type of the annotations to retrieve. /// An enumerable collection of annotations for this XObject. - public IEnumerable Annotations(Type type!!) + public IEnumerable Annotations(Type type) { + ArgumentNullException.ThrowIfNull(type); + return AnnotationsIterator(type); } @@ -250,8 +256,10 @@ public IEnumerable Annotations() where T : class /// Removes the annotations of the specified type from this . /// /// The type of annotations to remove. - public void RemoveAnnotations(Type type!!) + public void RemoveAnnotations(Type type) { + ArgumentNullException.ThrowIfNull(type); + if (annotations != null) { object?[]? a = annotations as object[]; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs index 77b4a539913c53..22c03644fc45f0 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs @@ -26,8 +26,10 @@ public class XProcessingInstruction : XNode /// /// Thrown if either the target or data parameter are null. /// - public XProcessingInstruction(string target, string data!!) + public XProcessingInstruction(string target, string data) { + ArgumentNullException.ThrowIfNull(data); + ValidateName(target); this.target = target; this.data = data; @@ -38,8 +40,10 @@ public XProcessingInstruction(string target, string data!!) /// from another XML processing instruction. /// /// XML processing instruction to copy from. - public XProcessingInstruction(XProcessingInstruction other!!) + public XProcessingInstruction(XProcessingInstruction other) { + ArgumentNullException.ThrowIfNull(other); + this.target = other.target; this.data = other.data; } @@ -113,8 +117,10 @@ public string Target /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteProcessingInstruction(target, data); } @@ -125,8 +131,10 @@ public override void WriteTo(XmlWriter writer!!) /// The to write this to. /// /// A cancellation token. - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return writer.WriteProcessingInstructionAsync(target, data); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs index 08dd0fc7c35a11..387337ab0cd8ad 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs @@ -21,8 +21,10 @@ public class XStreamingElement /// Creates a node with a given name /// /// The name to assign to the new node - public XStreamingElement(XName name!!) + public XStreamingElement(XName name) { + ArgumentNullException.ThrowIfNull(name); + this.name = name; } @@ -152,8 +154,10 @@ public void Save(TextWriter textWriter, SaveOptions options) /// Save the contents of an to an XML writer, not preserving whitespace /// /// to write to - public void Save(XmlWriter writer!!) + public void Save(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteStartDocument(); WriteTo(writer); writer.WriteEndDocument(); @@ -212,8 +216,10 @@ public string ToString(SaveOptions options) /// Write this to an /// /// - public void WriteTo(XmlWriter writer!!) + public void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + new StreamingElementWriter(writer).WriteStreamingElement(this); } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XText.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XText.cs index a6279f2fc4ece2..8737685eb75299 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XText.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XText.cs @@ -18,8 +18,10 @@ public class XText : XNode /// Initializes a new instance of the XText class. /// /// The string that contains the value of the text node. - public XText(string value!!) + public XText(string value) { + ArgumentNullException.ThrowIfNull(value); + text = value; } @@ -27,8 +29,10 @@ public XText(string value!!) /// Initializes a new instance of the XText class from another XText object. /// /// The text node to copy from. - public XText(XText other!!) + public XText(XText other) { + ArgumentNullException.ThrowIfNull(other); + text = other.text; } @@ -76,8 +80,10 @@ public string Value /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + if (parent is XDocument) { writer.WriteWhitespace(text); @@ -97,8 +103,10 @@ public override void WriteTo(XmlWriter writer!!) /// /// A cancellation token. /// - public override Task WriteToAsync(XmlWriter writer!!, CancellationToken cancellationToken) + public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(writer); + if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs index 752409ce7f6764..372c606ec74119 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs @@ -441,8 +441,10 @@ public static class Extensions /// Gets the schema information that has been assigned to the as a result of schema validation. /// /// Extension point - public static IXmlSchemaInfo? GetSchemaInfo(this XElement source!!) + public static IXmlSchemaInfo? GetSchemaInfo(this XElement source) { + ArgumentNullException.ThrowIfNull(source); + return source.Annotation(); } @@ -450,8 +452,10 @@ public static class Extensions /// Gets the schema information that has been assigned to the as a result of schema validation. /// /// Extension point - public static IXmlSchemaInfo? GetSchemaInfo(this XAttribute source!!) + public static IXmlSchemaInfo? GetSchemaInfo(this XAttribute source) { + ArgumentNullException.ThrowIfNull(source); + return source.Annotation(); } @@ -479,8 +483,11 @@ public static void Validate(this XDocument source, XmlSchemaSet schemas, Validat /// If enabled the and the corresponding /// subtree is augmented with PSVI in the form of annotations, /// default attributes and default element values - public static void Validate(this XDocument source!!, XmlSchemaSet schemas!!, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) + public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(schemas); + new XNodeValidator(schemas, validationEventHandler).Validate(source, null, addSchemaInfo); } @@ -514,8 +521,12 @@ public static void Validate(this XElement source, XmlSchemaObject partialValidat /// If enabled the and the corresponding /// subtree is augmented with PSVI in the form of annotations, /// default attributes and default element values - public static void Validate(this XElement source!!, XmlSchemaObject partialValidationType!!, XmlSchemaSet schemas!!, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) + public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(partialValidationType); + ArgumentNullException.ThrowIfNull(schemas); + new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo); } @@ -549,8 +560,12 @@ public static void Validate(this XAttribute source, XmlSchemaObject partialValid /// If enabled the is augmented with PSVI /// in the form of annotations, default attributes and /// default element values - public static void Validate(this XAttribute source!!, XmlSchemaObject partialValidationType!!, XmlSchemaSet schemas!!, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) + public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(partialValidationType); + ArgumentNullException.ThrowIfNull(schemas); + new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo); } } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs index af2db780461035..90b195833cb2a2 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs @@ -922,8 +922,10 @@ public static XPathNavigator CreateNavigator(this XNode node) /// The to be used by /// the /// An - public static XPathNavigator CreateNavigator(this XNode node!!, XmlNameTable? nameTable) + public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable? nameTable) { + ArgumentNullException.ThrowIfNull(node); + if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType)); XText? text = node as XText; if (text != null) @@ -955,8 +957,10 @@ public static object XPathEvaluate(this XNode node, string expression) /// prefixes used in the XPath expression /// The result of evaluating the expression which can be typed as bool, double, string or /// IEnumerable - public static object XPathEvaluate(this XNode node!!, string expression, IXmlNamespaceResolver? resolver) + public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver? resolver) { + ArgumentNullException.ThrowIfNull(node); + return XPathEvaluator.Evaluate(node, expression, resolver); } @@ -1003,8 +1007,10 @@ public static IEnumerable XPathSelectElements(this XNode node, string /// A for the namespace /// prefixes used in the XPath expression /// An corresponding to the resulting set of elements - public static IEnumerable XPathSelectElements(this XNode node!!, string expression, IXmlNamespaceResolver? resolver) + public static IEnumerable XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver? resolver) { + ArgumentNullException.ThrowIfNull(node); + return (IEnumerable)XPathEvaluator.Evaluate(node, expression, resolver); } diff --git a/src/libraries/System.Private.Xml.Linq/tests/Streaming/StreamExtensions.cs b/src/libraries/System.Private.Xml.Linq/tests/Streaming/StreamExtensions.cs index 054b50d7b3eafa..8d228de6cd9380 100644 --- a/src/libraries/System.Private.Xml.Linq/tests/Streaming/StreamExtensions.cs +++ b/src/libraries/System.Private.Xml.Linq/tests/Streaming/StreamExtensions.cs @@ -216,8 +216,12 @@ public static XElement LoadStream(TextReader textReader, XName rootName, params return LoadStream(XmlReader.Create(textReader, GetXmlReaderSettings()), rootName, streamNames); } - public static XElement LoadStream(XmlReader reader!!, XName rootName!!, params XName[] streamNames!!) + public static XElement LoadStream(XmlReader reader, XName rootName, params XName[] streamNames) { + ArgumentNullException.ThrowIfNull(reader); + ArgumentNullException.ThrowIfNull(rootName); + ArgumentNullException.ThrowIfNull(streamNames); + for (int i = 0; i < streamNames.Length; i++) { if (streamNames[i] == null) throw new ArgumentNullException("streamNames[" + i + "]"); @@ -234,15 +238,19 @@ public static XElement LoadStream(XmlReader reader!!, XName rootName!!, params X return source; } - public static IEnumerable Stream(this XElement source!!) + public static IEnumerable Stream(this XElement source) { + ArgumentNullException.ThrowIfNull(source); + StreamLoader loader = source.Annotation(); if (loader == null) throw new InvalidOperationException("No stream associated with the element."); return loader.Stream(source); } - public static IEnumerable Stream(this IEnumerable source!!) + public static IEnumerable Stream(this IEnumerable source) { + ArgumentNullException.ThrowIfNull(source); + return Enumerable.SelectMany(source, e => e.Stream()); } diff --git a/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/EventsHelper.cs b/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/EventsHelper.cs index e4e5a976998f58..b800517b42abac 100644 --- a/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/EventsHelper.cs +++ b/src/libraries/System.Private.Xml.Linq/tests/XDocument.Common/EventsHelper.cs @@ -202,8 +202,10 @@ public class UndoManager : IDisposable private bool _redoing; private int _lastGroup; - public UndoManager(XObject root!!) + public UndoManager(XObject root) { + ArgumentNullException.ThrowIfNull(root); + _root = root; _root.Changing += new EventHandler(Changing); _root.Changed += new EventHandler(Changed); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs index 6588b4f0e05284..1352e3e9f1b705 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs @@ -42,8 +42,10 @@ internal override bool IsFull } } - internal override int Decode(char[] chars!!, int startPos, int len) + internal override int Decode(char[] chars, int startPos, int len) { + ArgumentNullException.ThrowIfNull(chars); + if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); @@ -68,8 +70,10 @@ internal override int Decode(char[] chars!!, int startPos, int len) return charsDecoded; } - internal override int Decode(string str!!, int startPos, int len) + internal override int Decode(string str, int startPos, int len) { + ArgumentNullException.ThrowIfNull(str); + if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs index 7b1818693a2d2c..29007139db8b55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs @@ -22,8 +22,10 @@ internal Base64Encoder() internal abstract void WriteChars(char[] chars, int index, int count); - internal void Encode(byte[] buffer!!, int index, int count) + internal void Encode(byte[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs index 27012a54afeb9d..0b4a3d274a4402 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs @@ -12,71 +12,68 @@ internal abstract partial class Base64Encoder { internal abstract Task WriteCharsAsync(char[] chars, int index, int count); - internal async Task EncodeAsync(byte[] buffer!!, int index, int count) + internal Task EncodeAsync(byte[] buffer, int index, int count) { - if (index < 0) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } + return Core(buffer, index, count); - // encode left-over buffer - if (_leftOverBytesCount > 0) + async Task Core(byte[] buffer, int index, int count) { - int i = _leftOverBytesCount; - while (i < 3 && count > 0) + // encode left-over buffer + if (_leftOverBytesCount > 0) { - _leftOverBytes![i++] = buffer[index++]; - count--; - } + int i = _leftOverBytesCount; + while (i < 3 && count > 0) + { + _leftOverBytes![i++] = buffer[index++]; + count--; + } - // the total number of buffer we have is less than 3 -> return - if (count == 0 && i < 3) - { - _leftOverBytesCount = i; - return; - } + // the total number of buffer we have is less than 3 -> return + if (count == 0 && i < 3) + { + _leftOverBytesCount = i; + return; + } - // encode the left-over buffer and write out - int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); - await WriteCharsAsync(_charsLine, 0, leftOverChars).ConfigureAwait(false); - } - - // store new left-over buffer - _leftOverBytesCount = count % 3; - if (_leftOverBytesCount > 0) - { - count -= _leftOverBytesCount; - if (_leftOverBytes == null) - { - _leftOverBytes = new byte[3]; + // encode the left-over buffer and write out + int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); + await WriteCharsAsync(_charsLine, 0, leftOverChars).ConfigureAwait(false); } - for (int i = 0; i < _leftOverBytesCount; i++) + + // store new left-over buffer + _leftOverBytesCount = count % 3; + if (_leftOverBytesCount > 0) { - _leftOverBytes[i] = buffer[index + count + i]; + count -= _leftOverBytesCount; + if (_leftOverBytes == null) + { + _leftOverBytes = new byte[3]; + } + for (int i = 0; i < _leftOverBytesCount; i++) + { + _leftOverBytes[i] = buffer[index + count + i]; + } } - } - // encode buffer in 76 character long chunks - int endIndex = index + count; - int chunkSize = LineSizeInBytes; - while (index < endIndex) - { - if (index + chunkSize > endIndex) + // encode buffer in 76 character long chunks + int endIndex = index + count; + int chunkSize = LineSizeInBytes; + while (index < endIndex) { - chunkSize = endIndex - index; - } - int charCount = Convert.ToBase64CharArray(buffer, index, chunkSize, _charsLine, 0); - await WriteCharsAsync(_charsLine, 0, charCount).ConfigureAwait(false); + if (index + chunkSize > endIndex) + { + chunkSize = endIndex - index; + } + int charCount = Convert.ToBase64CharArray(buffer, index, chunkSize, _charsLine, 0); + await WriteCharsAsync(_charsLine, 0, charCount).ConfigureAwait(false); - index += chunkSize; + index += chunkSize; + } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs index 944e243424af85..352dfd92400b6f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs @@ -37,8 +37,10 @@ internal override bool IsFull } } - internal override int Decode(char[] chars!!, int startPos, int len) + internal override int Decode(char[] chars, int startPos, int len) { + ArgumentNullException.ThrowIfNull(chars); + if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); @@ -65,8 +67,10 @@ internal override int Decode(char[] chars!!, int startPos, int len) return charsDecoded; } - internal override int Decode(string str!!, int startPos, int len) + internal override int Decode(string str, int startPos, int len) { + ArgumentNullException.ThrowIfNull(str); + if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs index 77bd6d1ea9e3e0..dd0f19a19add8b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs @@ -7,8 +7,10 @@ internal static partial class BinHexEncoder { private const int CharsChunkSize = 128; - internal static void Encode(byte[] buffer!!, int index, int count, XmlWriter writer) + internal static void Encode(byte[] buffer, int index, int count, XmlWriter writer) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs index dcf46e3bccecba..6596c7f495bbbf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs @@ -7,30 +7,27 @@ namespace System.Xml { internal static partial class BinHexEncoder { - internal static async Task EncodeAsync(byte[] buffer!!, int index, int count, XmlWriter writer) + internal static Task EncodeAsync(byte[] buffer, int index, int count, XmlWriter writer) { - if (index < 0) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (count > buffer.Length - index) - { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } + return Core(buffer, index, count, writer); - char[] chars = new char[(count * 2) < CharsChunkSize ? (count * 2) : CharsChunkSize]; - int endIndex = index + count; - while (index < endIndex) + static async Task Core(byte[] buffer, int index, int count, XmlWriter writer) { - int cnt = (count < CharsChunkSize / 2) ? count : CharsChunkSize / 2; - HexConverter.EncodeToUtf16(buffer.AsSpan(index, cnt), chars); - await writer.WriteRawAsync(chars, 0, cnt * 2).ConfigureAwait(false); - index += cnt; - count -= cnt; + char[] chars = new char[(count * 2) < CharsChunkSize ? (count * 2) : CharsChunkSize]; + int endIndex = index + count; + while (index < endIndex) + { + int cnt = (count < CharsChunkSize / 2) ? count : CharsChunkSize / 2; + HexConverter.EncodeToUtf16(buffer.AsSpan(index, cnt), chars); + await writer.WriteRawAsync(chars, 0, cnt * 2).ConfigureAwait(false); + index += cnt; + count -= cnt; + } } } } // class diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentIterator.cs index dcab10a76dfe8a..9fbaeddd763f09 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentIterator.cs @@ -60,8 +60,10 @@ internal sealed class XPathDocumentElementChildIterator : XPathDocumentBaseItera /// /// Create an iterator that ranges over all element children of "parent" having the specified QName. /// - public XPathDocumentElementChildIterator(XPathDocumentNavigator parent, string name, string namespaceURI!!) : base(parent) + public XPathDocumentElementChildIterator(XPathDocumentNavigator parent, string name, string namespaceURI) : base(parent) { + ArgumentNullException.ThrowIfNull(namespaceURI); + _localName = parent.NameTable.Get(name); _namespaceUri = namespaceURI; } @@ -171,8 +173,10 @@ internal sealed class XPathDocumentElementDescendantIterator : XPathDocumentBase /// /// Create an iterator that ranges over all element descendants of "root" having the specified QName. /// - public XPathDocumentElementDescendantIterator(XPathDocumentNavigator root, string name, string namespaceURI!!, bool matchSelf) : base(root) + public XPathDocumentElementDescendantIterator(XPathDocumentNavigator root, string name, string namespaceURI, bool matchSelf) : base(root) { + ArgumentNullException.ThrowIfNull(namespaceURI); + _localName = root.NameTable.Get(name); _namespaceUri = namespaceURI; _matchSelf = matchSelf; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs index e376d5e6c78da5..7b8420a7908f57 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs @@ -60,9 +60,9 @@ internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelpe // Internal methods - internal int ReadContentAsBase64(byte[] buffer!!, int index, int count) + internal int ReadContentAsBase64(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -112,9 +112,9 @@ internal int ReadContentAsBase64(byte[] buffer!!, int index, int count) return ReadContentAsBinary(buffer, index, count); } - internal int ReadContentAsBinHex(byte[] buffer!!, int index, int count) + internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -164,9 +164,9 @@ internal int ReadContentAsBinHex(byte[] buffer!!, int index, int count) return ReadContentAsBinary(buffer, index, count); } - internal int ReadElementContentAsBase64(byte[] buffer!!, int index, int count) + internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -216,9 +216,9 @@ internal int ReadElementContentAsBase64(byte[] buffer!!, int index, int count) return ReadElementContentAsBinary(buffer, index, count); } - internal int ReadElementContentAsBinHex(byte[] buffer!!, int index, int count) + internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs index 0bde9d37029eea..0782d5f1674dd9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs @@ -10,20 +10,12 @@ internal sealed partial class ReadContentAsBinaryHelper { // Internal methods - internal async Task ReadContentAsBase64Async(byte[] buffer!!, int index, int count) + internal async Task ReadContentAsBase64Async(byte[] buffer, int index, int count) // only ever awaited, so no need to separate out argument handling { - // check arguments - if (count < 0) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } switch (_state) @@ -62,20 +54,12 @@ internal async Task ReadContentAsBase64Async(byte[] buffer!!, int index, in return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } - internal async Task ReadContentAsBinHexAsync(byte[] buffer!!, int index, int count) + internal async Task ReadContentAsBinHexAsync(byte[] buffer, int index, int count) // only ever awaited, so no need to separate out argument handling { - // check arguments - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } switch (_state) @@ -114,20 +98,12 @@ internal async Task ReadContentAsBinHexAsync(byte[] buffer!!, int index, in return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } - internal async Task ReadElementContentAsBase64Async(byte[] buffer!!, int index, int count) + internal async Task ReadElementContentAsBase64Async(byte[] buffer, int index, int count) // only ever awaited, so no need to separate out argument handling { - // check arguments - if (count < 0) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } switch (_state) @@ -166,20 +142,12 @@ internal async Task ReadElementContentAsBase64Async(byte[] buffer!!, int in return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } - internal async Task ReadElementContentAsBinHexAsync(byte[] buffer!!, int index, int count) + internal async Task ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) // only ever awaited, so no need to separate out argument handling { - // check arguments - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } switch (_state) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs index c8708fa6d6dfb0..6dd3669724df7d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs @@ -476,9 +476,9 @@ public override int ReadContentAsBinHex(byte[] buffer, int index, int count) return readCount; } - public override int ReadElementContentAsBase64(byte[] buffer!!, int index, int count) + public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -533,9 +533,9 @@ public override int ReadElementContentAsBase64(byte[] buffer!!, int index, int c return readCount; } - public override int ReadElementContentAsBinHex(byte[] buffer!!, int index, int count) + public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs index 7d49326315493f..92ec02ad6ec312 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs @@ -32,7 +32,11 @@ public override async Task ReadAsync() return false; case State.InReadBinary: - await FinishReadBinaryAsync().ConfigureAwait(false); + _state = State.Interactive; + if (_readBinaryHelper != null) + { + await _readBinaryHelper.FinishAsync().ConfigureAwait(false); + } _state = State.Interactive; goto case State.Interactive; @@ -299,125 +303,111 @@ public override async Task ReadContentAsBinHexAsync(byte[] buffer, int inde return readCount; } - public override async Task ReadElementContentAsBase64Async(byte[] buffer!!, int index, int count) + public override Task ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { - // check arguments - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) - { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } if (ReadState != ReadState.Interactive) { - return 0; + return Task.FromResult(0); } - if (_state != State.InReadBinary) + return Core(buffer, index, count); + + async Task Core(byte[] buffer, int index, int count) { - // forward ReadBase64Chunk calls into the base (wrapped) reader if possible, i.e. if it can read binary and we - // should not check characters - if (base.CanReadBinaryContent && (!_checkCharacters)) + if (_state != State.InReadBinary) { - _readBinaryHelper = null; - _state = State.InReadBinary; - return await base.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + // forward ReadBase64Chunk calls into the base (wrapped) reader if possible, i.e. if it can read binary and we + // should not check characters + if (base.CanReadBinaryContent && (!_checkCharacters)) + { + _readBinaryHelper = null; + _state = State.InReadBinary; + return await base.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + } + // the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore whitespace + else + { + _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); + } } - // the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore whitespace else { - _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); - } - } - else - { - // forward calls into wrapped reader - if (_readBinaryHelper == null) - { - return await base.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + // forward calls into wrapped reader + if (_readBinaryHelper == null) + { + return await base.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + } } - } - // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper - _state = State.Interactive; + // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper + _state = State.Interactive; - // call to the helper - int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); + // call to the helper + int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false); - // turn on InReadBinary in again and return - _state = State.InReadBinary; - return readCount; + // turn on InReadBinary in again and return + _state = State.InReadBinary; + return readCount; + } } - public override async Task ReadElementContentAsBinHexAsync(byte[] buffer!!, int index, int count) + public override Task ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { - // check arguments - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (buffer.Length - index < count) + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0 || (uint)count > buffer.Length - index) { - throw new ArgumentOutOfRangeException(nameof(count)); + throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count)); } + if (ReadState != ReadState.Interactive) { - return 0; + return Task.FromResult(0); } - if (_state != State.InReadBinary) + return Core(buffer, index, count); + + async Task Core(byte[] buffer, int index, int count) { - // forward ReadBinHexChunk calls into the base (wrapped) reader if possible, i.e. if it can read chunks and we - // should not check characters - if (base.CanReadBinaryContent && (!_checkCharacters)) + if (_state != State.InReadBinary) { - _readBinaryHelper = null; - _state = State.InReadBinary; - return await base.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + // forward ReadBinHexChunk calls into the base (wrapped) reader if possible, i.e. if it can read chunks and we + // should not check characters + if (base.CanReadBinaryContent && (!_checkCharacters)) + { + _readBinaryHelper = null; + _state = State.InReadBinary; + return await base.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + } + // the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore whitespace + else + { + _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); + } } - // the wrapped reader cannot read chunks or we are on an element where we should check characters or ignore whitespace else { - _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); - } - } - else - { - // forward calls into wrapped reader - if (_readBinaryHelper == null) - { - return await base.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + // forward calls into wrapped reader + if (_readBinaryHelper == null) + { + return await base.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + } } - } - // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper - _state = State.Interactive; + // turn off InReadBinary state in order to have a normal Read() behavior when called from readBinaryHelper + _state = State.Interactive; - // call to the helper - int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); + // call to the helper + int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false); - // turn on InReadBinary in again and return - _state = State.InReadBinary; - return readCount; - } - - private async Task FinishReadBinaryAsync() - { - _state = State.Interactive; - if (_readBinaryHelper != null) - { - await _readBinaryHelper.FinishAsync().ConfigureAwait(false); + // turn on InReadBinary in again and return + _state = State.InReadBinary; + return readCount; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index b0258cc26e4e70..64b0a2214b67bc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -269,8 +269,10 @@ public override void WriteSurrogateCharEntity(char lowChar, char highChar) writer.WriteSurrogateCharEntity(lowChar, highChar); } - public override void WriteChars(char[] buffer!!, int index, int count) + public override void WriteChars(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs index ce6515601ad644..20fa431666e261 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs @@ -217,8 +217,10 @@ public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) return writer.WriteSurrogateCharEntityAsync(lowChar, highChar); } - public override Task WriteCharsAsync(char[] buffer!!, int index, int count) + public override Task WriteCharsAsync(char[] buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs index f6246a9c4cbc3d..6fae9da36e80f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs @@ -184,8 +184,10 @@ public override void WriteRaw(string data) } // Override in order to handle Xml simple typed values and to pass resolver for QName values - public override void WriteValue(object value!!) + public override void WriteValue(object value) { + ArgumentNullException.ThrowIfNull(value); + WriteString(XmlUntypedConverter.Untyped.ToString(value, _resolver)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs index 4a345ca377bba3..9efea7bfb27c86 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs @@ -1634,8 +1634,10 @@ public static XmlReader Create(string inputUri, XmlReaderSettings? settings, Xml } // Creates an XmlReader according for parsing XML from the given stream. - public static XmlReader Create(Stream input!!) + public static XmlReader Create(Stream input) { + ArgumentNullException.ThrowIfNull(input); + // Avoid using XmlReader.Create(Stream, XmlReaderSettings), as it references a lot of types // that then can't be trimmed away. return new XmlTextReaderImpl(input, null, 0, XmlReaderSettings.s_defaultReaderSettings, null, string.Empty, null, false); @@ -1662,8 +1664,10 @@ public static XmlReader Create(Stream input, XmlReaderSettings? settings, XmlPar } // Creates an XmlReader according for parsing XML from the given TextReader. - public static XmlReader Create(TextReader input!!) + public static XmlReader Create(TextReader input) { + ArgumentNullException.ThrowIfNull(input); + // Avoid using XmlReader.Create(TextReader, XmlReaderSettings), as it references a lot of types // that then can't be trimmed away. return new XmlTextReaderImpl(input, XmlReaderSettings.s_defaultReaderSettings, string.Empty, null); @@ -1699,8 +1703,10 @@ public static XmlReader Create(XmlReader reader, XmlReaderSettings? settings) // !!!!!! // NOTE: This method is called via reflection from System.Data.Common.dll. // !!!!!! - internal static XmlReader CreateSqlReader(Stream input!!, XmlReaderSettings? settings, XmlParserContext inputContext) + internal static XmlReader CreateSqlReader(Stream input, XmlReaderSettings? settings, XmlParserContext inputContext) { + ArgumentNullException.ThrowIfNull(input); + settings ??= XmlReaderSettings.s_defaultReaderSettings; XmlReader reader; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs index 8280e0201088ca..68adf4d128807b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs @@ -340,8 +340,10 @@ internal XmlReader CreateReader(string inputUri, XmlParserContext? inputContext) return reader; } - internal XmlReader CreateReader(Stream input!!, Uri? baseUri, string? baseUriString, XmlParserContext? inputContext) + internal XmlReader CreateReader(Stream input, Uri? baseUri, string? baseUriString, XmlParserContext? inputContext) { + ArgumentNullException.ThrowIfNull(input); + baseUriString ??= baseUri?.ToString() ?? string.Empty; // create text XML reader @@ -361,8 +363,10 @@ internal XmlReader CreateReader(Stream input!!, Uri? baseUri, string? baseUriStr return reader; } - internal XmlReader CreateReader(TextReader input!!, string? baseUriString, XmlParserContext? inputContext) + internal XmlReader CreateReader(TextReader input, string? baseUriString, XmlParserContext? inputContext) { + ArgumentNullException.ThrowIfNull(input); + baseUriString ??= string.Empty; // create xml text reader @@ -382,8 +386,10 @@ internal XmlReader CreateReader(TextReader input!!, string? baseUriString, XmlPa return reader; } - internal XmlReader CreateReader(XmlReader reader!!) + internal XmlReader CreateReader(XmlReader reader) { + ArgumentNullException.ThrowIfNull(reader); + return AddValidationAndConformanceWrapper(reader); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs index 1dc9d284561316..aebe458c33f3f5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs @@ -1580,8 +1580,10 @@ private void FinishReadContentAsType() } } - private static void CheckBuffer(Array buffer!!, int index, int count) + private static void CheckBuffer(Array buffer, int index, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs index 52d924a6c491df..32d9d35cf8baa4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs @@ -107,8 +107,10 @@ internal void WriteSurrogateChar(char lowChar, char highChar) _textWriter.Write(lowChar); } - internal void Write(char[] array!!, int offset, int count) + internal void Write(char[] array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (0 > offset) { throw new ArgumentOutOfRangeException(nameof(offset)); @@ -442,8 +444,10 @@ internal void WriteRawWithSurrogateChecking(string text) return; } - internal void WriteRaw(char[] array!!, int offset, int count) + internal void WriteRaw(char[] array, int offset, int count) { + ArgumentNullException.ThrowIfNull(array); + if (0 > count) { throw new ArgumentOutOfRangeException(nameof(count)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index 97d01af0afba91..5173cc001bb1ee 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -1596,9 +1596,9 @@ public override bool CanReadBinaryContent } // Reads and concatenates content nodes, base64-decodes the results and copies the decoded bytes into the provided buffer - public override int ReadContentAsBase64(byte[] buffer!!, int index, int count) + public override int ReadContentAsBase64(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -1652,9 +1652,9 @@ public override int ReadContentAsBase64(byte[] buffer!!, int index, int count) // Reads and concatenates content nodes, binhex-decodes the results and copies the decoded bytes into the provided buffer - public override int ReadContentAsBinHex(byte[] buffer!!, int index, int count) + public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -1707,9 +1707,9 @@ public override int ReadContentAsBinHex(byte[] buffer!!, int index, int count) } // Reads and concatenates content of an element, base64-decodes the results and copies the decoded bytes into the provided buffer - public override int ReadElementContentAsBase64(byte[] buffer!!, int index, int count) + public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -1763,9 +1763,9 @@ public override int ReadElementContentAsBase64(byte[] buffer!!, int index, int c // Reads and concatenates content of an element, binhex-decodes the results and copies the decoded bytes into the provided buffer - public override int ReadElementContentAsBinHex(byte[] buffer!!, int index, int count) + public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { - // check arguments + ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -1834,7 +1834,6 @@ public override int ReadValueChunk(char[] buffer, int index, int count) { throw new InvalidOperationException(SR.Format(SR.Xml_InvalidReadValueChunk, _curNode.type)); } - // check arguments ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index a068979c9ab98e..6257fa4678d737 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -387,7 +387,6 @@ private async Task ReadContentAsBase64_AsyncHelper(Task task, byte[] public override Task ReadContentAsBase64Async(byte[] buffer, int index, int count) { CheckAsyncCall(); - // check arguments ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { @@ -453,7 +452,6 @@ public override Task ReadContentAsBase64Async(byte[] buffer, int index, int public override async Task ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { CheckAsyncCall(); - // check arguments ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { @@ -528,7 +526,6 @@ private async Task ReadElementContentAsBase64Async_Helper(Task task, public override Task ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { CheckAsyncCall(); - // check arguments ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { @@ -594,7 +591,6 @@ public override Task ReadElementContentAsBase64Async(byte[] buffer, int ind public override async Task ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { CheckAsyncCall(); - // check arguments ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { @@ -656,7 +652,6 @@ public override async Task ReadValueChunkAsync(char[] buffer, int index, in { throw new InvalidOperationException(SR.Format(SR.Xml_InvalidReadValueChunk, _curNode.type)); } - // check arguments ArgumentNullException.ThrowIfNull(buffer); if (count < 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs index fe9785cbf495ab..ba97d84b7c114e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs @@ -28,14 +28,18 @@ public XmlValidatingReader(XmlReader reader) _impl.OuterReader = this; } - public XmlValidatingReader([StringSyntax(StringSyntaxAttribute.Xml)] string xmlFragment!!, XmlNodeType fragType, XmlParserContext context) + public XmlValidatingReader([StringSyntax(StringSyntaxAttribute.Xml)] string xmlFragment, XmlNodeType fragType, XmlParserContext context) { + ArgumentNullException.ThrowIfNull(xmlFragment); + _impl = new XmlValidatingReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; } - public XmlValidatingReader(Stream xmlFragment!!, XmlNodeType fragType, XmlParserContext context) + public XmlValidatingReader(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) { + ArgumentNullException.ThrowIfNull(xmlFragment); + _impl = new XmlValidatingReaderImpl(xmlFragment, fragType, context); _impl.OuterReader = this; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs index eb45d2e1e82b4b..bbb8badf40ccf8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs @@ -243,8 +243,10 @@ public virtual void WriteQualifiedName(string localName, string? ns) } // Writes out the specified value. - public virtual void WriteValue(object value!!) + public virtual void WriteValue(object value) { + ArgumentNullException.ThrowIfNull(value); + WriteString(XmlUntypedConverter.Untyped.ToString(value, null)); } @@ -311,8 +313,10 @@ public virtual void WriteValue(long value) // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. - public virtual void WriteAttributes(XmlReader reader!!, bool defattr) + public virtual void WriteAttributes(XmlReader reader, bool defattr) { + ArgumentNullException.ThrowIfNull(reader); + if (reader.NodeType is XmlNodeType.Element or XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) @@ -354,8 +358,10 @@ public virtual void WriteAttributes(XmlReader reader!!, bool defattr) // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. - public virtual void WriteNode(XmlReader reader!!, bool defattr) + public virtual void WriteNode(XmlReader reader, bool defattr) { + ArgumentNullException.ThrowIfNull(reader); + bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do @@ -416,8 +422,10 @@ public virtual void WriteNode(XmlReader reader!!, bool defattr) } // Copies the current node from the given XPathNavigator to the writer (including child nodes). - public virtual void WriteNode(XPathNavigator navigator!!, bool defattr) + public virtual void WriteNode(XPathNavigator navigator, bool defattr) { + ArgumentNullException.ThrowIfNull(navigator); + int iLevel = 0; navigator = navigator.Clone(); @@ -605,8 +613,10 @@ private void WriteLocalNamespaces(XPathNavigator nsNav) // Static methods for creating writers // // Creates an XmlWriter for writing into the provided file. - public static XmlWriter Create(string outputFileName!!) + public static XmlWriter Create(string outputFileName) { + ArgumentNullException.ThrowIfNull(outputFileName); + // Avoid using XmlWriter.Create(string, XmlReaderSettings), as it references a lot of types // that then can't be trimmed away. var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read); @@ -631,8 +641,10 @@ public static XmlWriter Create(string outputFileName, XmlWriterSettings? setting } // Creates an XmlWriter for writing into the provided stream. - public static XmlWriter Create(Stream output!!) + public static XmlWriter Create(Stream output) { + ArgumentNullException.ThrowIfNull(output); + // Avoid using XmlWriter.Create(Stream, XmlReaderSettings), as it references a lot of types // that then can't be trimmed away. XmlWriterSettings settings = XmlWriterSettings.s_defaultWriterSettings; @@ -648,8 +660,10 @@ public static XmlWriter Create(Stream output, XmlWriterSettings? settings) } // Creates an XmlWriter for writing into the provided TextWriter. - public static XmlWriter Create(TextWriter output!!) + public static XmlWriter Create(TextWriter output) { + ArgumentNullException.ThrowIfNull(output); + // Avoid using XmlWriter.Create(TextWriter, XmlReaderSettings), as it references a lot of types // that then can't be trimmed away. XmlWriterSettings settings = XmlWriterSettings.s_defaultWriterSettings; @@ -665,16 +679,20 @@ public static XmlWriter Create(TextWriter output, XmlWriterSettings? settings) } // Creates an XmlWriter for writing into the provided StringBuilder. - public static XmlWriter Create(StringBuilder output!!) + public static XmlWriter Create(StringBuilder output) { + ArgumentNullException.ThrowIfNull(output); + // Avoid using XmlWriter.Create(StringBuilder, XmlReaderSettings), as it references a lot of types // that then can't be trimmed away. return Create(new StringWriter(output, CultureInfo.InvariantCulture)); } // Creates an XmlWriter for writing into the provided StringBuilder with the specified settings. - public static XmlWriter Create(StringBuilder output!!, XmlWriterSettings? settings) + public static XmlWriter Create(StringBuilder output, XmlWriterSettings? settings) { + ArgumentNullException.ThrowIfNull(output); + settings ??= XmlWriterSettings.s_defaultWriterSettings; return settings.CreateWriter(new StringWriter(output, CultureInfo.InvariantCulture)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs index ce4fc852872bc8..a2bc43bfa0a5c3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs @@ -231,51 +231,59 @@ public virtual async Task WriteQualifiedNameAsync(string localName, string? ns) // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. - public virtual async Task WriteAttributesAsync(XmlReader reader!!, bool defattr) + public virtual Task WriteAttributesAsync(XmlReader reader, bool defattr) { - if (reader.NodeType is XmlNodeType.Element or XmlNodeType.XmlDeclaration) + ArgumentNullException.ThrowIfNull(reader); + return Core(reader, defattr); + + async Task Core(XmlReader reader, bool defattr) { - if (reader.MoveToFirstAttribute()) + if (reader.NodeType is XmlNodeType.Element or XmlNodeType.XmlDeclaration) { - await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); - reader.MoveToElement(); + if (reader.MoveToFirstAttribute()) + { + await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); + reader.MoveToElement(); + } } - } - else if (reader.NodeType != XmlNodeType.Attribute) - { - throw new XmlException(SR.Xml_InvalidPosition, string.Empty); - } - else - { - do + else if (reader.NodeType != XmlNodeType.Attribute) { - // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. - // If either of these is true and defattr=false, we should not write the attribute out - if (defattr || !reader.IsDefaultInternal) + throw new XmlException(SR.Xml_InvalidPosition, string.Empty); + } + else + { + do { - await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); - while (reader.ReadAttributeValue()) + // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. + // If either of these is true and defattr=false, we should not write the attribute out + if (defattr || !reader.IsDefaultInternal) { - if (reader.NodeType == XmlNodeType.EntityReference) - { - await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); - } - else + await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); + while (reader.ReadAttributeValue()) { - await WriteStringAsync(reader.Value).ConfigureAwait(false); + if (reader.NodeType == XmlNodeType.EntityReference) + { + await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); + } + else + { + await WriteStringAsync(reader.Value).ConfigureAwait(false); + } } + await WriteEndAttributeAsync().ConfigureAwait(false); } - await WriteEndAttributeAsync().ConfigureAwait(false); } + while (reader.MoveToNextAttribute()); } - while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. - public virtual Task WriteNodeAsync(XmlReader reader!!, bool defattr) + public virtual Task WriteNodeAsync(XmlReader reader, bool defattr) { + ArgumentNullException.ThrowIfNull(reader); + if (reader.Settings is { Async: true }) { return WriteNodeAsync_CallAsyncReader(reader, defattr); @@ -411,119 +419,125 @@ internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defatt } // Copies the current node from the given XPathNavigator to the writer (including child nodes). - public virtual async Task WriteNodeAsync(XPathNavigator navigator!!, bool defattr) + public virtual Task WriteNodeAsync(XPathNavigator navigator, bool defattr) { - int iLevel = 0; - - navigator = navigator.Clone(); + ArgumentNullException.ThrowIfNull(navigator); + return Core(navigator, defattr); - while (true) + async Task Core(XPathNavigator navigator, bool defattr) { - bool mayHaveChildren = false; - XPathNodeType nodeType = navigator.NodeType; + int iLevel = 0; - switch (nodeType) + navigator = navigator.Clone(); + + while (true) { - case XPathNodeType.Element: - await WriteStartElementAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); + bool mayHaveChildren = false; + XPathNodeType nodeType = navigator.NodeType; - // Copy attributes - if (navigator.MoveToFirstAttribute()) - { - do + switch (nodeType) + { + case XPathNodeType.Element: + await WriteStartElementAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); + + // Copy attributes + if (navigator.MoveToFirstAttribute()) { - IXmlSchemaInfo? schemaInfo = navigator.SchemaInfo; - if (defattr || (schemaInfo == null || !schemaInfo.IsDefault)) + do { - await WriteStartAttributeAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); - // copy string value to writer - await WriteStringAsync(navigator.Value).ConfigureAwait(false); - await WriteEndAttributeAsync().ConfigureAwait(false); - } - } while (navigator.MoveToNextAttribute()); - navigator.MoveToParent(); - } - - // Copy namespaces - if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local)) - { - await WriteLocalNamespacesAsync(navigator).ConfigureAwait(false); - navigator.MoveToParent(); - } - mayHaveChildren = true; - break; - case XPathNodeType.Attribute: - // do nothing on root level attribute - break; - case XPathNodeType.Text: - await WriteStringAsync(navigator.Value).ConfigureAwait(false); - break; - case XPathNodeType.SignificantWhitespace: - case XPathNodeType.Whitespace: - await WriteWhitespaceAsync(navigator.Value).ConfigureAwait(false); - break; - case XPathNodeType.Root: - mayHaveChildren = true; - break; - case XPathNodeType.Comment: - await WriteCommentAsync(navigator.Value).ConfigureAwait(false); - break; - case XPathNodeType.ProcessingInstruction: - await WriteProcessingInstructionAsync(navigator.LocalName, navigator.Value).ConfigureAwait(false); - break; - case XPathNodeType.Namespace: - // do nothing on root level namespace - break; - default: - Debug.Fail($"Unexpected node type {nodeType}"); - break; - } + IXmlSchemaInfo? schemaInfo = navigator.SchemaInfo; + if (defattr || (schemaInfo == null || !schemaInfo.IsDefault)) + { + await WriteStartAttributeAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); + // copy string value to writer + await WriteStringAsync(navigator.Value).ConfigureAwait(false); + await WriteEndAttributeAsync().ConfigureAwait(false); + } + } while (navigator.MoveToNextAttribute()); + navigator.MoveToParent(); + } - if (mayHaveChildren) - { - // If children exist, move down to next level - if (navigator.MoveToFirstChild()) - { - iLevel++; - continue; + // Copy namespaces + if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local)) + { + await WriteLocalNamespacesAsync(navigator).ConfigureAwait(false); + navigator.MoveToParent(); + } + mayHaveChildren = true; + break; + case XPathNodeType.Attribute: + // do nothing on root level attribute + break; + case XPathNodeType.Text: + await WriteStringAsync(navigator.Value).ConfigureAwait(false); + break; + case XPathNodeType.SignificantWhitespace: + case XPathNodeType.Whitespace: + await WriteWhitespaceAsync(navigator.Value).ConfigureAwait(false); + break; + case XPathNodeType.Root: + mayHaveChildren = true; + break; + case XPathNodeType.Comment: + await WriteCommentAsync(navigator.Value).ConfigureAwait(false); + break; + case XPathNodeType.ProcessingInstruction: + await WriteProcessingInstructionAsync(navigator.LocalName, navigator.Value).ConfigureAwait(false); + break; + case XPathNodeType.Namespace: + // do nothing on root level namespace + break; + default: + Debug.Fail($"Unexpected node type {nodeType}"); + break; } - // EndElement - if (navigator.NodeType == XPathNodeType.Element) + if (mayHaveChildren) { - if (navigator.IsEmptyElement) + // If children exist, move down to next level + if (navigator.MoveToFirstChild()) { - await WriteEndElementAsync().ConfigureAwait(false); + iLevel++; + continue; } - else + + // EndElement + if (navigator.NodeType == XPathNodeType.Element) { - await WriteFullEndElementAsync().ConfigureAwait(false); + if (navigator.IsEmptyElement) + { + await WriteEndElementAsync().ConfigureAwait(false); + } + else + { + await WriteFullEndElementAsync().ConfigureAwait(false); + } } } - } - // No children - while (true) - { - if (iLevel == 0) + // No children + while (true) { - // The entire subtree has been copied - return; - } + if (iLevel == 0) + { + // The entire subtree has been copied + return; + } - if (navigator.MoveToNext()) - { - // Found a sibling, so break to outer loop - break; - } + if (navigator.MoveToNext()) + { + // Found a sibling, so break to outer loop + break; + } - // No siblings, so move up to previous level - iLevel--; - navigator.MoveToParent(); + // No siblings, so move up to previous level + iLevel--; + navigator.MoveToParent(); - // EndElement - if (navigator.NodeType == XPathNodeType.Element) - await WriteFullEndElementAsync().ConfigureAwait(false); + // EndElement + if (navigator.NodeType == XPathNodeType.Element) + await WriteFullEndElementAsync().ConfigureAwait(false); + } } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs index bd0afc62a28440..11492a32b99786 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs @@ -332,8 +332,10 @@ internal bool AutoXmlDeclaration // method will default to Indent=true for Html and Indent=false for Xml. internal TriState IndentInternal { get; set; } private bool IsQuerySpecific => CDataSectionElements.Count != 0 || _docTypePublic != null || _docTypeSystem != null || _standalone == XmlStandalone.Yes; - internal XmlWriter CreateWriter(string outputFileName!!) + internal XmlWriter CreateWriter(string outputFileName) { + ArgumentNullException.ThrowIfNull(outputFileName); + // need to clone the settigns so that we can set CloseOutput to true to make sure the stream gets closed in the end XmlWriterSettings newSettings = this; if (!newSettings.CloseOutput) @@ -358,8 +360,10 @@ internal XmlWriter CreateWriter(string outputFileName!!) } } - internal XmlWriter CreateWriter(Stream output!!) + internal XmlWriter CreateWriter(Stream output) { + ArgumentNullException.ThrowIfNull(output); + XmlWriter writer; // create raw writer @@ -431,8 +435,10 @@ internal XmlWriter CreateWriter(Stream output!!) return writer; } - internal XmlWriter CreateWriter(TextWriter output!!) + internal XmlWriter CreateWriter(TextWriter output) { + ArgumentNullException.ThrowIfNull(output); + XmlWriter writer; // create raw writer @@ -475,8 +481,10 @@ internal XmlWriter CreateWriter(TextWriter output!!) return writer; } - internal XmlWriter CreateWriter(XmlWriter output!!) + internal XmlWriter CreateWriter(XmlWriter output) { + ArgumentNullException.ThrowIfNull(output); + return AddConformanceWrapper(output); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs index b6e9a6ef233505..1484ff0a609969 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs @@ -38,8 +38,10 @@ public override XPathNavigator Clone() return new DocumentXPathNavigator(this); } - public override void SetValue(string value!!) + public override void SetValue(string value) { + ArgumentNullException.ThrowIfNull(value); + XmlNode node = _source; XmlNode end; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index e46ee02a196143..8c660bc7d0c84e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -1133,8 +1133,10 @@ public class XmlNodeReader : XmlReader, IXmlNamespaceResolver // Creates an instance of the XmlNodeReader class using the specified XmlNode. - public XmlNodeReader(XmlNode node!!) + public XmlNodeReader(XmlNode node) { + ArgumentNullException.ThrowIfNull(node); + _readerNav = new XmlNodeReaderNavigator(node); _curDepth = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs index 886cd5df3cc66a..e51f58c54b151e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs @@ -244,7 +244,9 @@ public override String Get( String value!! ) { return Get( ref name ); } - public override String Get( char[] key!!, int start, int len ) { + public override String Get( char[] key, int start, int len ) { + ArgumentNullException.ThrowIfNull(key); + if ((start < 0) || (len < 0) || (start > key.Length - len)) throw new ArgumentOutOfRangeException(); @@ -294,12 +296,16 @@ private String Get( ref MTNameTableName nn ) { // Find the matching string atom given a string, or // insert a new one. - public override String Add(String value!!) { + public override String Add(String value) { + ArgumentNullException.ThrowIfNull(value); + MTNameTableName name = new MTNameTableName( value ); return Add( ref name, rwLock != null ).value; } - public override String Add(char[] key!!, int start, int len) { + public override String Add(char[] key, int start, int len) { + ArgumentNullException.ThrowIfNull(key); + if ((start < 0) || (len < 0) || (start > key.Length - len)) throw new ArgumentOutOfRangeException(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs index 0f8e6d52b5b97c..e708bb83770c6c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -51,8 +51,10 @@ public NameTable() /// Add the given string to the NameTable or return /// the existing string if it is already in the NameTable. /// - public override string Add(string key!!) + public override string Add(string key) { + ArgumentNullException.ThrowIfNull(key); + int len = key.Length; if (len == 0) { @@ -113,8 +115,10 @@ public override string Add(char[] key, int start, int len) /// /// Find the matching string in the NameTable. /// - public override string? Get(string value!!) + public override string? Get(string value) { + ArgumentNullException.ThrowIfNull(value); + if (value.Length == 0) { return string.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs index 884c21218c0cec..6f72340dd9a818 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs @@ -222,8 +222,10 @@ public override Uri ResolveUri(Uri? baseUri, string? relativeUri) return base.ResolveUri(baseUri, relativeUri); } - public override object? GetEntity(Uri absoluteUri!!, string? role, Type? ofObjectToReturn) + public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn) { + ArgumentNullException.ThrowIfNull(absoluteUri); + PreloadedData? data; if (!_mappings.TryGetValue(absoluteUri, out data)) { @@ -260,8 +262,10 @@ public override ICredentials Credentials } } - public override bool SupportsType(Uri absoluteUri!!, Type? type) + public override bool SupportsType(Uri absoluteUri, Type? type) { + ArgumentNullException.ThrowIfNull(absoluteUri); + PreloadedData? data; if (!_mappings.TryGetValue(absoluteUri, out data)) { @@ -275,13 +279,19 @@ public override bool SupportsType(Uri absoluteUri!!, Type? type) return data.SupportsType(type); } - public void Add(Uri uri!!, byte[] value!!) + public void Add(Uri uri, byte[] value) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(value); + Add(uri, new ByteArrayChunk(value, 0, value.Length)); } - public void Add(Uri uri!!, byte[] value!!, int offset, int count) + public void Add(Uri uri, byte[] value, int offset, int count) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(value); + if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -298,8 +308,11 @@ public void Add(Uri uri!!, byte[] value!!, int offset, int count) Add(uri, new ByteArrayChunk(value, offset, count)); } - public void Add(Uri uri!!, Stream value!!) + public void Add(Uri uri, Stream value) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(value); + if (value.CanSeek) { // stream of known length -> allocate the byte array and read all data into it @@ -325,8 +338,11 @@ public void Add(Uri uri!!, Stream value!!) } } - public void Add(Uri uri!!, string value!!) + public void Add(Uri uri, string value) { + ArgumentNullException.ThrowIfNull(uri); + ArgumentNullException.ThrowIfNull(value); + Add(uri, new StringData(value)); } @@ -341,10 +357,7 @@ public IEnumerable PreloadedUris public void Remove(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); _mappings.Remove(uri); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs index 5a037d4c9afe07..296a39d9e70167 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs @@ -14,10 +14,12 @@ namespace System.Xml.Resolvers // public partial class XmlPreloadedResolver : XmlResolver { - public override Task GetEntityAsync(Uri absoluteUri!!, + public override Task GetEntityAsync(Uri absoluteUri, string? role, Type? ofObjectToReturn) { + ArgumentNullException.ThrowIfNull(absoluteUri); + PreloadedData? data; if (!_mappings.TryGetValue(absoluteUri, out data)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs index 0ce5a74e90ba42..f54c99d57773cb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs @@ -575,8 +575,10 @@ internal override object ParseValue(string s, XmlNameTable? nameTable, IXmlNames } } - internal override Exception? TryParseValue(object value!!, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) + internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) { + ArgumentNullException.ThrowIfNull(value); + Exception? exception; typedValue = null; @@ -1035,8 +1037,10 @@ internal override RestrictionFlags ValidRestrictionFlags } internal DatatypeImplementation ItemType { get { return _itemType; } } - internal override Exception? TryParseValue(object value!!, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) + internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) { + ArgumentNullException.ThrowIfNull(value); + Exception? exception; string? s = value as string; typedValue = null; @@ -1294,8 +1298,10 @@ internal bool IsUnionBaseOf(DatatypeImplementation derivedType) return exception; } - internal override Exception? TryParseValue(object value!!, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) + internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { + ArgumentNullException.ThrowIfNull(value); + Exception? exception; typedValue = null; string? s = value as string; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index 25b5014b2260d5..fa8790edd65905 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -175,8 +175,10 @@ public XmlSchemaSet InferSchema(XmlReader instanceDocument, XmlSchemaSet schemas return InferSchema1(instanceDocument, schemas); } - internal XmlSchemaSet InferSchema1(XmlReader instanceDocument!!, XmlSchemaSet schemas) + internal XmlSchemaSet InferSchema1(XmlReader instanceDocument, XmlSchemaSet schemas) { + ArgumentNullException.ThrowIfNull(instanceDocument); + _rootSchema = null; _xtr = instanceDocument; schemas.Compile(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs index 7988c3fa2412b9..a4a213dd865cf0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs @@ -78,49 +78,65 @@ public IDictionary GetNamespacesInScope(XmlNamespaceScope scope) // XmlAtomicValue constructors and methods //----------------------------------------------- - internal XmlAtomicValue(XmlSchemaType xmlType!!, bool value) + internal XmlAtomicValue(XmlSchemaType xmlType, bool value) { + ArgumentNullException.ThrowIfNull(xmlType); + _xmlType = xmlType; _clrType = TypeCode.Boolean; _unionVal.boolVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, DateTime value) + internal XmlAtomicValue(XmlSchemaType xmlType, DateTime value) { + ArgumentNullException.ThrowIfNull(xmlType); + _xmlType = xmlType; _clrType = TypeCode.DateTime; _unionVal.dtVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, double value) + internal XmlAtomicValue(XmlSchemaType xmlType, double value) { + ArgumentNullException.ThrowIfNull(xmlType); + _xmlType = xmlType; _clrType = TypeCode.Double; _unionVal.dblVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, int value) + internal XmlAtomicValue(XmlSchemaType xmlType, int value) { + ArgumentNullException.ThrowIfNull(xmlType); + _xmlType = xmlType; _clrType = TypeCode.Int32; _unionVal.i32Val = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, long value) + internal XmlAtomicValue(XmlSchemaType xmlType, long value) { + ArgumentNullException.ThrowIfNull(xmlType); + _xmlType = xmlType; _clrType = TypeCode.Int64; _unionVal.i64Val = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, string value!!) + internal XmlAtomicValue(XmlSchemaType xmlType, string value) { + ArgumentNullException.ThrowIfNull(xmlType); + ArgumentNullException.ThrowIfNull(value); + _xmlType = xmlType; _objVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, string value!!, IXmlNamespaceResolver? nsResolver) + internal XmlAtomicValue(XmlSchemaType xmlType, string value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(xmlType); + ArgumentNullException.ThrowIfNull(value); + _xmlType = xmlType; _objVal = value; if (nsResolver != null && (_xmlType.TypeCode == XmlTypeCode.QName || _xmlType.TypeCode == XmlTypeCode.Notation)) @@ -130,14 +146,20 @@ internal XmlAtomicValue(XmlSchemaType xmlType!!, string value!!, IXmlNamespaceRe } } - internal XmlAtomicValue(XmlSchemaType xmlType!!, object value!!) + internal XmlAtomicValue(XmlSchemaType xmlType, object value) { + ArgumentNullException.ThrowIfNull(xmlType); + ArgumentNullException.ThrowIfNull(value); + _xmlType = xmlType; _objVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType!!, object value!!, IXmlNamespaceResolver? nsResolver) + internal XmlAtomicValue(XmlSchemaType xmlType, object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(xmlType); + ArgumentNullException.ThrowIfNull(value); + _xmlType = xmlType; _objVal = value; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs index d025c9ddec087c..9381147780298c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs @@ -43,8 +43,10 @@ public XmlSchemaCollection() : this(new NameTable()) /// Construct a new empty schema collection with associated XmlNameTable. /// The XmlNameTable is used when loading schemas. /// - public XmlSchemaCollection(XmlNameTable nametable!!) + public XmlSchemaCollection(XmlNameTable nametable) { + ArgumentNullException.ThrowIfNull(nametable); + _nameTable = nametable; _collection = Hashtable.Synchronized(new Hashtable()); _xmlResolver = null; @@ -122,8 +124,10 @@ internal XmlResolver? XmlResolver /// If the given schema references other namespaces, the schemas for those /// other namespaces are NOT automatically loaded. /// - public XmlSchema? Add(string? ns, XmlReader reader!!, XmlResolver? resolver) + public XmlSchema? Add(string? ns, XmlReader reader, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(reader); + XmlNameTable readerNameTable = reader.NameTable; SchemaInfo schemaInfo = new SchemaInfo(); @@ -156,8 +160,10 @@ internal XmlResolver? XmlResolver return Add(schema, _xmlResolver); } - public XmlSchema? Add(XmlSchema schema!!, XmlResolver? resolver) + public XmlSchema? Add(XmlSchema schema, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(schema); + SchemaInfo schemaInfo = new SchemaInfo(); schemaInfo.SchemaType = SchemaType.XSD; return Add(schema.TargetNamespace, schemaInfo, schema, true, resolver); @@ -167,8 +173,10 @@ internal XmlResolver? XmlResolver /// Adds all the namespaces defined in the given collection /// (including their associated schemas) to this collection. /// - public void Add(XmlSchemaCollection schema!!) + public void Add(XmlSchemaCollection schema) { + ArgumentNullException.ThrowIfNull(schema); + if (this == schema) return; IDictionaryEnumerator enumerator = schema._collection.GetEnumerator(); @@ -192,8 +200,10 @@ public XmlSchema? this[string? ns] } } - public bool Contains(XmlSchema schema!!) + public bool Contains(XmlSchema schema) { + ArgumentNullException.ThrowIfNull(schema); + return this[schema.TargetNamespace] != null; } @@ -215,8 +225,10 @@ public XmlSchemaCollectionEnumerator GetEnumerator() return new XmlSchemaCollectionEnumerator(_collection); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) @@ -229,8 +241,10 @@ void ICollection.CopyTo(Array array!!, int index) } } - public void CopyTo(XmlSchema[] array!!, int index) + public void CopyTo(XmlSchema[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs index 8ad704851686fc..28c2aedb6ba86c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs @@ -23,13 +23,20 @@ public abstract class XmlSchemaDatatype internal XmlSchemaDatatype() { } - public virtual object ChangeType(object value!!, Type targetType!!) + public virtual object ChangeType(object value, Type targetType) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(targetType); + return ValueConverter.ChangeType(value, targetType); } - public virtual object ChangeType(object value!!, Type targetType!!, IXmlNamespaceResolver namespaceResolver!!) + public virtual object ChangeType(object value, Type targetType, IXmlNamespaceResolver namespaceResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(targetType); + ArgumentNullException.ThrowIfNull(namespaceResolver); + return ValueConverter.ChangeType(value, targetType, namespaceResolver); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs index 62ee7612bb5bf0..138e2b529fe0a9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs @@ -186,8 +186,10 @@ public bool IsSynchronized } } - public void CopyTo(Array array!!, int arrayIndex) + public void CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); @@ -238,8 +240,10 @@ public bool IsSynchronized } } - public void CopyTo(Array array!!, int arrayIndex) + public void CopyTo(Array array, int arrayIndex) { + ArgumentNullException.ThrowIfNull(array); + if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs index f680e1d84570d1..5c9011e1aea6fa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs @@ -84,8 +84,10 @@ public XmlSchemaSet() : this(new NameTable()) /// Construct a new empty schema schemas with associated XmlNameTable. /// The XmlNameTable is used when loading schemas. /// - public XmlSchemaSet(XmlNameTable nameTable!!) + public XmlSchemaSet(XmlNameTable nameTable) { + ArgumentNullException.ThrowIfNull(nameTable); + _nameTable = nameTable; _schemas = new SortedList(); @@ -319,8 +321,10 @@ internal XmlSchemaObjectTable TypeExtensions /// If the given schema references other namespaces, the schemas for those /// other namespaces are NOT automatically loaded. /// - public XmlSchema? Add(string? targetNamespace, XmlReader schemaDocument!!) + public XmlSchema? Add(string? targetNamespace, XmlReader schemaDocument) { + ArgumentNullException.ThrowIfNull(schemaDocument); + if (targetNamespace != null) { targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace); @@ -349,8 +353,10 @@ internal XmlSchemaObjectTable TypeExtensions /// Adds all the namespaces defined in the given schemas /// (including their associated schemas) to this schemas. /// - public void Add(XmlSchemaSet schemas!!) + public void Add(XmlSchemaSet schemas) { + ArgumentNullException.ThrowIfNull(schemas); + if (this == schemas) { return; @@ -431,8 +437,10 @@ public void Add(XmlSchemaSet schemas!!) } } - public XmlSchema? Add(XmlSchema schema!!) + public XmlSchema? Add(XmlSchema schema) { + ArgumentNullException.ThrowIfNull(schema); + lock (InternalSyncObject) { if (_schemas.ContainsKey(schema.SchemaId)) @@ -449,8 +457,10 @@ public void Add(XmlSchemaSet schemas!!) return Remove(schema, true); } - public bool RemoveRecursive(XmlSchema schemaToRemove!!) + public bool RemoveRecursive(XmlSchema schemaToRemove) { + ArgumentNullException.ThrowIfNull(schemaToRemove); + if (!_schemas.ContainsKey(schemaToRemove.SchemaId)) { return false; @@ -528,8 +538,10 @@ public bool Contains(string? targetNamespace) return _targetNamespaces[targetNamespace] != null; } - public bool Contains(XmlSchema schema!!) + public bool Contains(XmlSchema schema) { + ArgumentNullException.ThrowIfNull(schema); + return _schemas.ContainsValue(schema); } @@ -628,8 +640,10 @@ public void Compile() return; } - public XmlSchema Reprocess(XmlSchema schema!!) + public XmlSchema Reprocess(XmlSchema schema) { + ArgumentNullException.ThrowIfNull(schema); + // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Remove, Add and AddSchemaToSet // methods. If you change anything here *make sure* to update Remove/Add/AddSchemaToSet method(s) accordingly. // The only difference is that we don't touch .schemas collection here to not break a code like this: @@ -715,8 +729,10 @@ public XmlSchema Reprocess(XmlSchema schema!!) } } - public void CopyTo(XmlSchema[] schemas!!, int index) + public void CopyTo(XmlSchema[] schemas, int index) { + ArgumentNullException.ThrowIfNull(schemas); + if (index < 0 || index > schemas.Length - 1) throw new ArgumentOutOfRangeException(nameof(index)); _schemas.Values.CopyTo(schemas, index); @@ -846,8 +862,10 @@ private bool AddToCompiledInfo(XmlSchema schema, SchemaInfo newCompiledInfo, ref #endif //For use by the validator when loading schemaLocations in the instance - internal void Add(string? targetNamespace, XmlReader reader!!, Hashtable validatedNamespaces) + internal void Add(string? targetNamespace, XmlReader reader, Hashtable validatedNamespaces) { + ArgumentNullException.ThrowIfNull(reader); + if (targetNamespace == null) { targetNamespace = string.Empty; @@ -1080,8 +1098,10 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro substitutionGroup.Members.Add(headElement); } - internal XmlSchema? Remove(XmlSchema schema!!, bool forceCompile) + internal XmlSchema? Remove(XmlSchema schema, bool forceCompile) { + ArgumentNullException.ThrowIfNull(schema); + // Due to bug 644477 - this method is tightly coupled (THE CODE IS BASICALLY COPIED) to Reprocess // method. If you change anything here *make sure* to update Reprocess method accordingly. lock (InternalSyncObject) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs index d11d5381da19b6..de3bea2daabc16 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs @@ -29,8 +29,10 @@ public class XmlSchemaType : XmlSchemaAnnotated /// /// [To be supplied.] /// - public static XmlSchemaSimpleType? GetBuiltInSimpleType(XmlQualifiedName qualifiedName!!) + public static XmlSchemaSimpleType? GetBuiltInSimpleType(XmlQualifiedName qualifiedName) { + ArgumentNullException.ThrowIfNull(qualifiedName); + return DatatypeImplementation.GetSimpleTypeFromXsdType(qualifiedName); } @@ -58,8 +60,10 @@ public static XmlSchemaSimpleType GetBuiltInSimpleType(XmlTypeCode typeCode) /// /// [To be supplied.] /// - public static XmlSchemaComplexType? GetBuiltInComplexType(XmlQualifiedName qualifiedName!!) + public static XmlSchemaComplexType? GetBuiltInComplexType(XmlQualifiedName qualifiedName) { + ArgumentNullException.ThrowIfNull(qualifiedName); + if (qualifiedName.Equals(XmlSchemaComplexType.AnyType.QualifiedName)) { return XmlSchemaComplexType.AnyType; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 4a618dfc983b2a..45ae2c306a04af 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -159,8 +159,12 @@ public sealed class XmlSchemaValidator private static readonly string[] s_methodNames = new string[12] { "None", "Initialize", "top-level ValidateAttribute", "top-level ValidateText or ValidateWhitespace", "ValidateElement", "ValidateAttribute", "ValidateEndOfAttributes", "ValidateText", "ValidateWhitespace", "ValidateEndElement", "SkipToEndElement", "EndValidation" }; - public XmlSchemaValidator(XmlNameTable nameTable!!, XmlSchemaSet schemas!!, IXmlNamespaceResolver namespaceResolver!!, XmlSchemaValidationFlags validationFlags) + public XmlSchemaValidator(XmlNameTable nameTable, XmlSchemaSet schemas, IXmlNamespaceResolver namespaceResolver, XmlSchemaValidationFlags validationFlags) { + ArgumentNullException.ThrowIfNull(nameTable); + ArgumentNullException.ThrowIfNull(schemas); + ArgumentNullException.ThrowIfNull(namespaceResolver); + _nameTable = nameTable; _nsResolver = namespaceResolver; _validationFlags = validationFlags; @@ -315,8 +319,10 @@ public event ValidationEventHandler? ValidationEventHandler } //Methods - public void AddSchema(XmlSchema schema!!) + public void AddSchema(XmlSchema schema) { + ArgumentNullException.ThrowIfNull(schema); + if ((_validationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) == 0) { //Do not process schema if processInlineSchema is not set return; @@ -398,8 +404,11 @@ public void ValidateElement(string localName, string namespaceUri, XmlSchemaInfo ValidateElement(localName, namespaceUri, schemaInfo, null, null, null, null); } - public void ValidateElement(string localName!!, string namespaceUri!!, XmlSchemaInfo? schemaInfo, string? xsiType, string? xsiNil, string? xsiSchemaLocation, string? xsiNoNamespaceSchemaLocation) + public void ValidateElement(string localName, string namespaceUri, XmlSchemaInfo? schemaInfo, string? xsiType, string? xsiNil, string? xsiSchemaLocation, string? xsiNoNamespaceSchemaLocation) { + ArgumentNullException.ThrowIfNull(localName); + ArgumentNullException.ThrowIfNull(namespaceUri); + CheckStateTransition(ValidatorState.Element, s_methodNames[(int)ValidatorState.Element]); ClearPSVI(); @@ -478,18 +487,25 @@ public void ValidateElement(string localName!!, string namespaceUri!!, XmlSchema } } - public object? ValidateAttribute(string localName, string namespaceUri, string attributeValue!!, XmlSchemaInfo? schemaInfo) + public object? ValidateAttribute(string localName, string namespaceUri, string attributeValue, XmlSchemaInfo? schemaInfo) { + ArgumentNullException.ThrowIfNull(attributeValue); + return ValidateAttribute(localName, namespaceUri, null, attributeValue, schemaInfo); } - public object? ValidateAttribute(string localName, string namespaceUri, XmlValueGetter attributeValue!!, XmlSchemaInfo? schemaInfo) + public object? ValidateAttribute(string localName, string namespaceUri, XmlValueGetter attributeValue, XmlSchemaInfo? schemaInfo) { + ArgumentNullException.ThrowIfNull(attributeValue); + return ValidateAttribute(localName, namespaceUri, attributeValue, null, schemaInfo); } - private object? ValidateAttribute(string localName!!, string namespaceUri!!, XmlValueGetter? attributeValueGetter, string? attributeStringValue, XmlSchemaInfo? schemaInfo) + private object? ValidateAttribute(string localName, string namespaceUri, XmlValueGetter? attributeValueGetter, string? attributeStringValue, XmlSchemaInfo? schemaInfo) { + ArgumentNullException.ThrowIfNull(localName); + ArgumentNullException.ThrowIfNull(namespaceUri); + ValidatorState toState = _validationStack.Length > 1 ? ValidatorState.Attribute : ValidatorState.TopLevelAttribute; CheckStateTransition(toState, s_methodNames[(int)toState]); @@ -696,8 +712,10 @@ public void ValidateElement(string localName!!, string namespaceUri!!, XmlSchema return typedVal; } - public void GetUnspecifiedDefaultAttributes(ArrayList defaultAttributes!!) + public void GetUnspecifiedDefaultAttributes(ArrayList defaultAttributes) { + ArgumentNullException.ThrowIfNull(defaultAttributes); + CheckStateTransition(ValidatorState.Attribute, "GetUnspecifiedDefaultAttributes"); GetUnspecifiedDefaultAttributes(defaultAttributes, false); } @@ -718,13 +736,17 @@ public void ValidateEndOfAttributes(XmlSchemaInfo? schemaInfo) } } - public void ValidateText(string elementValue!!) + public void ValidateText(string elementValue) { + ArgumentNullException.ThrowIfNull(elementValue); + ValidateText(elementValue, null); } - public void ValidateText(XmlValueGetter elementValue!!) + public void ValidateText(XmlValueGetter elementValue) { + ArgumentNullException.ThrowIfNull(elementValue); + ValidateText(null, elementValue); } @@ -793,13 +815,17 @@ private void ValidateText(string? elementStringValue, XmlValueGetter? elementVal } } - public void ValidateWhitespace(string elementValue!!) + public void ValidateWhitespace(string elementValue) { + ArgumentNullException.ThrowIfNull(elementValue); + ValidateWhitespace(elementValue, null); } - public void ValidateWhitespace(XmlValueGetter elementValue!!) + public void ValidateWhitespace(XmlValueGetter elementValue) { + ArgumentNullException.ThrowIfNull(elementValue); + ValidateWhitespace(null, elementValue); } @@ -858,8 +884,10 @@ private void ValidateWhitespace(string? elementStringValue, XmlValueGetter? elem return InternalValidateEndElement(schemaInfo, null); } - public object? ValidateEndElement(XmlSchemaInfo? schemaInfo, object typedValue!!) + public object? ValidateEndElement(XmlSchemaInfo? schemaInfo, object typedValue) { + ArgumentNullException.ThrowIfNull(typedValue); + if (_textValue.Length > 0) { throw new InvalidOperationException(SR.Sch_InvalidEndElementCall); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs index f7189737c8cec5..9a9e08e4c38584 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs @@ -874,13 +874,17 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLNUMERIC10CONVERTER - public override decimal ToDecimal(string value!!) + public override decimal ToDecimal(string value) { + ArgumentNullException.ThrowIfNull(value); + if (TypeCode == XmlTypeCode.Decimal) return XmlConvert.ToDecimal((string)value); return XmlConvert.ToInteger((string)value); } - public override decimal ToDecimal(object value!!) + public override decimal ToDecimal(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DecimalType) return ((decimal)value); @@ -895,13 +899,17 @@ public override int ToInt32(long value) { return Int64ToInt32((long)value); } - public override int ToInt32(string value!!) + public override int ToInt32(string value) { + ArgumentNullException.ThrowIfNull(value); + if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt32(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt32((string)value); } - public override int ToInt32(object value!!) + public override int ToInt32(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt32((decimal)value); @@ -916,13 +924,17 @@ public override long ToInt64(int value) { return ((long)(int)value); } - public override long ToInt64(string value!!) + public override long ToInt64(string value) { + ArgumentNullException.ThrowIfNull(value); + if (TypeCode == XmlTypeCode.Decimal) return DecimalToInt64(XmlConvert.ToDecimal((string)value)); return XmlConvert.ToInt64((string)value); } - public override long ToInt64(object value!!) + public override long ToInt64(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt64((decimal)value); @@ -959,8 +971,10 @@ public override string ToString(long value) { return XmlConvert.ToString((long)value); } - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DecimalType) return this.ToString((decimal)value); @@ -977,8 +991,10 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(decimal value, Type destinationType!!) + public override object ChangeType(decimal value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)value); if (destinationType == Int32Type) return DecimalToInt32((decimal)value); @@ -990,8 +1006,10 @@ public override object ChangeType(decimal value, Type destinationType!!) return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(int value, Type destinationType!!) + public override object ChangeType(int value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(int)value); if (destinationType == Int32Type) return ((int)value); @@ -1003,8 +1021,10 @@ public override object ChangeType(int value, Type destinationType!!) return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(long value, Type destinationType!!) + public override object ChangeType(long value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return ((decimal)(long)value); if (destinationType == Int32Type) return Int64ToInt32((long)value); @@ -1016,8 +1036,11 @@ public override object ChangeType(long value, Type destinationType!!) return ChangeTypeWildcardSource(value, destinationType!, null); } - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DecimalType) return this.ToDecimal((string)value); if (destinationType == Int32Type) return this.ToInt32((string)value); @@ -1029,8 +1052,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeTypeWildcardSource(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1114,13 +1140,17 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLNUMERIC2CONVERTER - public override double ToDouble(string value!!) + public override double ToDouble(string value) { + ArgumentNullException.ThrowIfNull(value); + if (TypeCode == XmlTypeCode.Float) return ((double)XmlConvert.ToSingle((string)value)); return XmlConvert.ToDouble((string)value); } - public override double ToDouble(object value!!) + public override double ToDouble(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((double)value); @@ -1154,13 +1184,17 @@ public override float ToSingle(double value) { return ((float)(double)value); } - public override float ToSingle(string value!!) + public override float ToSingle(string value) { + ArgumentNullException.ThrowIfNull(value); + if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToSingle((string)value); return ((float)XmlConvert.ToDouble((string)value)); } - public override float ToSingle(object value!!) + public override float ToSingle(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((float)(double)value); @@ -1186,8 +1220,10 @@ public override string ToString(float value) if (TypeCode == XmlTypeCode.Float) return XmlConvert.ToString((float)value); return XmlConvert.ToString((double)(float)value); } - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DoubleType) return this.ToString((double)value); @@ -1203,8 +1239,10 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(double value, Type destinationType!!) + public override object ChangeType(double value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return ((double)value); if (destinationType == SingleType) return ((float)(double)value); @@ -1215,8 +1253,11 @@ public override object ChangeType(double value, Type destinationType!!) return ChangeListType(value, destinationType, null); } - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble((string)value); if (destinationType == SingleType) return this.ToSingle((string)value); @@ -1227,8 +1268,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeListType(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1273,8 +1317,10 @@ public override DateTime ToDateTime(DateTimeOffset value) return DateTimeOffsetToDateTime(value); } - public override DateTime ToDateTime(string value!!) + public override DateTime ToDateTime(string value) { + ArgumentNullException.ThrowIfNull(value); + return TypeCode switch { XmlTypeCode.Date => StringToDate((string)value), @@ -1287,8 +1333,10 @@ public override DateTime ToDateTime(string value!!) _ => StringToDateTime((string)value), }; } - public override DateTime ToDateTime(object value!!) + public override DateTime ToDateTime(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ((DateTime)value); @@ -1308,8 +1356,10 @@ public override DateTimeOffset ToDateTimeOffset(DateTime value) return new DateTimeOffset(value); } - public override DateTimeOffset ToDateTimeOffset(string value!!) + public override DateTimeOffset ToDateTimeOffset(string value) { + ArgumentNullException.ThrowIfNull(value); + return TypeCode switch { XmlTypeCode.Date => StringToDateOffset((string)value), @@ -1323,8 +1373,10 @@ public override DateTimeOffset ToDateTimeOffset(string value!!) }; } - public override DateTimeOffset ToDateTimeOffset(object value!!) + public override DateTimeOffset ToDateTimeOffset(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ToDateTimeOffset((DateTime)value); @@ -1400,8 +1452,10 @@ public override string ToString(DateTimeOffset value) => _ => DateTimeOffsetToString((DateTimeOffset)value), }; - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == DateTimeType) return this.ToString((DateTime)value); @@ -1417,8 +1471,10 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(DateTime value, Type destinationType!!) + public override object ChangeType(DateTime value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return ((DateTime)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((DateTime)value); @@ -1429,8 +1485,11 @@ public override object ChangeType(DateTime value, Type destinationType!!) return ChangeListType(value, destinationType, null); } - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime((string)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((string)value); @@ -1441,8 +1500,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeListType(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1481,12 +1543,16 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLBOOLEANCONVERTER - public override bool ToBoolean(string value!!) + public override bool ToBoolean(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToBoolean((string)value); } - public override bool ToBoolean(object value!!) + public override bool ToBoolean(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == BooleanType) return ((bool)value); @@ -1547,8 +1613,10 @@ public override string ToString(bool value) { return XmlConvert.ToString((bool)value); } - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); @@ -1563,8 +1631,10 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(bool value, Type destinationType!!) + public override object ChangeType(bool value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return ((bool)value); if (destinationType == StringType) return XmlConvert.ToString((bool)value); @@ -1574,8 +1644,11 @@ public override object ChangeType(bool value, Type destinationType!!) return ChangeListType(value, destinationType, null); } - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == StringType) return ((string)value); @@ -1585,8 +1658,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeListType(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1622,8 +1698,10 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLMISCCONVERTER - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == ByteArrayType) @@ -1662,8 +1740,11 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) { @@ -1697,8 +1778,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeTypeWildcardSource(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1843,8 +1927,10 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLSTRINGCONVERTER - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return ((string)value); @@ -1858,8 +1944,11 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); @@ -1868,8 +1957,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeListType(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1913,12 +2005,16 @@ private XmlUntypedConverter(XmlUntypedConverter atomicConverter, bool allowListT // ToBoolean //----------------------------------------------- - public override bool ToBoolean(string value!!) + public override bool ToBoolean(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToBoolean((string)value); } - public override bool ToBoolean(object value!!) + public override bool ToBoolean(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); @@ -1931,12 +2027,16 @@ public override bool ToBoolean(object value!!) // ToDateTime //----------------------------------------------- - public override DateTime ToDateTime(string value!!) + public override DateTime ToDateTime(string value) { + ArgumentNullException.ThrowIfNull(value); + return UntypedAtomicToDateTime((string)value); } - public override DateTime ToDateTime(object value!!) + public override DateTime ToDateTime(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTime((string)value); @@ -1948,13 +2048,17 @@ public override DateTime ToDateTime(object value!!) // ToDateTimeOffset //----------------------------------------------- - public override DateTimeOffset ToDateTimeOffset(string value!!) + public override DateTimeOffset ToDateTimeOffset(string value) { + ArgumentNullException.ThrowIfNull(value); + return UntypedAtomicToDateTimeOffset((string)value); } - public override DateTimeOffset ToDateTimeOffset(object value!!) + public override DateTimeOffset ToDateTimeOffset(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTimeOffset((string)value); @@ -1966,12 +2070,16 @@ public override DateTimeOffset ToDateTimeOffset(object value!!) // ToDecimal //----------------------------------------------- - public override decimal ToDecimal(string value!!) + public override decimal ToDecimal(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToDecimal((string)value); } - public override decimal ToDecimal(object value!!) + public override decimal ToDecimal(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDecimal((string)value); @@ -1984,12 +2092,16 @@ public override decimal ToDecimal(object value!!) // ToDouble //----------------------------------------------- - public override double ToDouble(string value!!) + public override double ToDouble(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToDouble((string)value); } - public override double ToDouble(object value!!) + public override double ToDouble(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDouble((string)value); @@ -2002,12 +2114,16 @@ public override double ToDouble(object value!!) // ToInt32 //----------------------------------------------- - public override int ToInt32(string value!!) + public override int ToInt32(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToInt32((string)value); } - public override int ToInt32(object value!!) + public override int ToInt32(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt32((string)value); @@ -2020,12 +2136,16 @@ public override int ToInt32(object value!!) // ToInt64 //----------------------------------------------- - public override long ToInt64(string value!!) + public override long ToInt64(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToInt64((string)value); } - public override long ToInt64(object value!!) + public override long ToInt64(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt64((string)value); @@ -2038,12 +2158,16 @@ public override long ToInt64(object value!!) // ToSingle //----------------------------------------------- - public override float ToSingle(string value!!) + public override float ToSingle(string value) { + ArgumentNullException.ThrowIfNull(value); + return XmlConvert.ToSingle((string)value); } - public override float ToSingle(object value!!) + public override float ToSingle(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToSingle((string)value); @@ -2088,8 +2212,10 @@ public override string ToString(float value) { return XmlConvert.ToString((float)value); } - public override string ToString(object value!!, IXmlNamespaceResolver? nsResolver) + public override string ToString(object value, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); @@ -2121,56 +2247,71 @@ public override string ToString(object value!!, IXmlNamespaceResolver? nsResolve // ChangeType //----------------------------------------------- - public override object ChangeType(bool value, Type destinationType!!) + public override object ChangeType(bool value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((bool)value); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(DateTime value, Type destinationType!!) + public override object ChangeType(DateTime value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return DateTimeToString((DateTime)value); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(decimal value, Type destinationType!!) + public override object ChangeType(decimal value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((decimal)value); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(double value, Type destinationType!!) + public override object ChangeType(double value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((double)value); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(int value, Type destinationType!!) + public override object ChangeType(int value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((int)value); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(long value, Type destinationType!!) + public override object ChangeType(long value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return XmlConvert.ToString((long)value); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == ByteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); @@ -2197,8 +2338,11 @@ public override object ChangeType(string value!!, Type destinationType!!, IXmlNa return ChangeTypeWildcardSource(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -2379,8 +2523,10 @@ private XmlAnyConverter(XmlTypeCode typeCode) : base(typeCode) // ToBoolean //----------------------------------------------- - public override bool ToBoolean(object value!!) + public override bool ToBoolean(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; @@ -2393,8 +2539,10 @@ public override bool ToBoolean(object value!!) // ToDateTime //----------------------------------------------- - public override DateTime ToDateTime(object value!!) + public override DateTime ToDateTime(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; @@ -2406,8 +2554,10 @@ public override DateTime ToDateTime(object value!!) // ToDateTimeOffset //----------------------------------------------- - public override DateTimeOffset ToDateTimeOffset(object value!!) + public override DateTimeOffset ToDateTimeOffset(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return (DateTimeOffset)((XmlAtomicValue)value).ValueAs(DateTimeOffsetType); @@ -2420,8 +2570,10 @@ public override DateTimeOffset ToDateTimeOffset(object value!!) // ToDecimal //----------------------------------------------- - public override decimal ToDecimal(object value!!) + public override decimal ToDecimal(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); @@ -2434,8 +2586,10 @@ public override decimal ToDecimal(object value!!) // ToDouble //----------------------------------------------- - public override double ToDouble(object value!!) + public override double ToDouble(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; @@ -2448,8 +2602,10 @@ public override double ToDouble(object value!!) // ToInt32 //----------------------------------------------- - public override int ToInt32(object value!!) + public override int ToInt32(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; @@ -2462,8 +2618,10 @@ public override int ToInt32(object value!!) // ToInt64 //----------------------------------------------- - public override long ToInt64(object value!!) + public override long ToInt64(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; @@ -2476,8 +2634,10 @@ public override long ToInt64(object value!!) // ToSingle //----------------------------------------------- - public override float ToSingle(object value!!) + public override float ToSingle(object value) { + ArgumentNullException.ThrowIfNull(value); + Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); @@ -2497,64 +2657,82 @@ public override float ToSingle(object value!!) // ChangeType //----------------------------------------------- - public override object ChangeType(bool value, Type destinationType!!) + public override object ChangeType(bool value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), (bool)value)); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(DateTime value, Type destinationType!!) + public override object ChangeType(DateTime value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime), (DateTime)value)); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(decimal value, Type destinationType!!) + public override object ChangeType(decimal value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), value)); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(double value, Type destinationType!!) + public override object ChangeType(double value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), (double)value)); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(int value, Type destinationType!!) + public override object ChangeType(int value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Int), (int)value)); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(long value, Type destinationType!!) + public override object ChangeType(long value, Type destinationType) { + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Long), (long)value)); return ChangeTypeWildcardSource(value, destinationType, null); } - public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), (string)value)); return ChangeTypeWildcardSource(value, destinationType, nsResolver); } - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -2675,8 +2853,11 @@ private XmlAnyListConverter(XmlBaseConverter atomicConverter) : base(atomicConve // ChangeType //----------------------------------------------- - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + // If source value does not implement IEnumerable, or it is a string or byte[], if (!(value is IEnumerable) || value.GetType() == StringType || value.GetType() == ByteArrayType) { @@ -2728,8 +2909,11 @@ public static XmlValueConverter Create(XmlValueConverter atomicConverter) // ChangeType //----------------------------------------------- - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + return ChangeListType(value, destinationType, nsResolver); } @@ -2967,8 +3151,11 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) // ChangeType //----------------------------------------------- - public override object ChangeType(object value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(object value, Type destinationType, IXmlNamespaceResolver? nsResolver) { + ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(destinationType); + Type sourceType = value.GetType(); // If source value is an XmlAtomicValue, then allow it to perform the conversion diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs index 2fb7a24efc65d9..0cffc2174d1c12 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs @@ -13,9 +13,11 @@ internal static class TypeExtensions public static bool TryConvertTo( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] - this Type targetType!!, + this Type targetType, object? data, out object? returnValue) { + ArgumentNullException.ThrowIfNull(targetType); + returnValue = null; if (data == null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index e03003879a650d..e947009ac7d934 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -165,8 +165,10 @@ public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root) /// [To be supplied.] /// [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - public XmlTypeMapping ImportTypeMapping(Type type!!, XmlRootAttribute? root, string? defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root, string? defaultNamespace) { + ArgumentNullException.ThrowIfNull(type); + XmlTypeMapping xmlMapping = new XmlTypeMapping(_typeScope, ImportElement(_modelScope.GetTypeModel(type), root, defaultNamespace, new RecursionLimiter())); xmlMapping.SetKeyInternal(XmlMapping.GenerateKey(type, root, defaultNamespace)); xmlMapping.GenerateSerializer = true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index cf2beede639599..cc50d72f09a71d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -189,8 +189,10 @@ public XmlSerializer(Type type, XmlAttributeOverrides? overrides) : this(type, o } [RequiresUnreferencedCode(TrimSerializationWarning)] - public XmlSerializer(XmlTypeMapping xmlTypeMapping!!) + public XmlSerializer(XmlTypeMapping xmlTypeMapping) { + ArgumentNullException.ThrowIfNull(xmlTypeMapping); + if (Mode != SerializationMode.ReflectionOnly) { _tempAssembly = GenerateTempAssembly(xmlTypeMapping); @@ -204,8 +206,10 @@ public XmlSerializer(Type type) : this(type, (string?)null) } [RequiresUnreferencedCode(TrimSerializationWarning)] - public XmlSerializer(Type type!!, string? defaultNamespace) + public XmlSerializer(Type type, string? defaultNamespace) { + ArgumentNullException.ThrowIfNull(type); + DefaultNamespace = defaultNamespace; _rootType = type; @@ -263,8 +267,10 @@ public XmlSerializer(Type type!!, string? defaultNamespace) } [RequiresUnreferencedCode(TrimSerializationWarning)] - public XmlSerializer(Type type!!, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) + public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { + ArgumentNullException.ThrowIfNull(type); + DefaultNamespace = defaultNamespace; _rootType = type; _mapping = GenerateXmlTypeMapping(type, overrides, extraTypes, root, defaultNamespace); @@ -300,8 +306,10 @@ private static XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOver } [RequiresUnreferencedCode("creates TempAssembly")] - internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping!!, Type? type, string? defaultNamespace, string? location) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace, string? location) { + ArgumentNullException.ThrowIfNull(xmlMapping); + xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { @@ -731,8 +739,10 @@ public static string GetXmlSerializerAssemblyName(Type type) return GetXmlSerializerAssemblyName(type, null); } - public static string GetXmlSerializerAssemblyName(Type type!!, string? defaultNamespace) + public static string GetXmlSerializerAssemblyName(Type type, string? defaultNamespace) { + ArgumentNullException.ThrowIfNull(type); + return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs index 8fe6921dce1f0a..7f003332d5fc21 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs @@ -27,8 +27,11 @@ public XPathAxisIterator(XPathNavigator nav, XPathNodeType type, bool matchSelf) this.type = type; } - public XPathAxisIterator(XPathNavigator nav, string name!!, string namespaceURI!!, bool matchSelf) : this(nav, matchSelf) + public XPathAxisIterator(XPathNavigator nav, string name, string namespaceURI, bool matchSelf) : this(nav, matchSelf) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(namespaceURI); + this.name = name; this.uri = namespaceURI; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs index c33642777ef2ed..62458a0837faa9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs @@ -49,8 +49,10 @@ internal XPathDocument() /// /// Create a new empty document. All names should be atomized using "nameTable". /// - internal XPathDocument(XmlNameTable nameTable!!) + internal XPathDocument(XmlNameTable nameTable) { + ArgumentNullException.ThrowIfNull(nameTable); + _nameTable = nameTable; } @@ -64,8 +66,10 @@ public XPathDocument(XmlReader reader) : this(reader, XmlSpace.Default) /// /// Create a new document from "reader", with whitespace handling controlled according to "space". /// - public XPathDocument(XmlReader reader!!, XmlSpace space) + public XPathDocument(XmlReader reader, XmlSpace space) { + ArgumentNullException.ThrowIfNull(reader); + LoadFromReader(reader, space); } @@ -141,8 +145,10 @@ internal XmlRawWriter LoadFromWriter(LoadFlags flags, string baseUri) /// can be passed to indicate that names should be atomized by the builder and/or a fragment should be created. /// [MemberNotNull(nameof(_nameTable))] - internal void LoadFromReader(XmlReader reader!!, XmlSpace space) + internal void LoadFromReader(XmlReader reader, XmlSpace space) { + ArgumentNullException.ThrowIfNull(reader); + XPathDocumentBuilder builder; IXmlLineInfo? lineInfo; string? xmlnsUri; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index 1d6c7591fcbc61..8baa5565a5ccc6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -109,8 +109,10 @@ public override object TypedValue } } - public virtual void SetTypedValue(object typedValue!!) + public virtual void SetTypedValue(object typedValue) { + ArgumentNullException.ThrowIfNull(typedValue); + switch (NodeType) { case XPathNodeType.Element: @@ -600,8 +602,10 @@ public virtual XmlReader ReadSubtree() return CreateReader(); } - public virtual void WriteSubtree(XmlWriter writer!!) + public virtual void WriteSubtree(XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + writer.WriteNode(this, true); } @@ -1335,8 +1339,10 @@ public virtual void ReplaceSelf(string newNode) ReplaceSelf(reader); } - public virtual void ReplaceSelf(XmlReader newNode!!) + public virtual void ReplaceSelf(XmlReader newNode) { + ArgumentNullException.ThrowIfNull(newNode); + XPathNodeType type = NodeType; if (type == XPathNodeType.Root || type == XPathNodeType.Attribute @@ -1349,8 +1355,10 @@ public virtual void ReplaceSelf(XmlReader newNode!!) writer.Close(); } - public virtual void ReplaceSelf(XPathNavigator newNode!!) + public virtual void ReplaceSelf(XPathNavigator newNode) { + ArgumentNullException.ThrowIfNull(newNode); + XmlReader reader = newNode.CreateReader(); ReplaceSelf(reader); } @@ -1484,15 +1492,19 @@ public virtual void AppendChild(string newChild) AppendChild(reader); } - public virtual void AppendChild(XmlReader newChild!!) + public virtual void AppendChild(XmlReader newChild) { + ArgumentNullException.ThrowIfNull(newChild); + XmlWriter writer = AppendChild(); BuildSubtree(newChild, writer); writer.Close(); } - public virtual void AppendChild(XPathNavigator newChild!!) + public virtual void AppendChild(XPathNavigator newChild) { + ArgumentNullException.ThrowIfNull(newChild); + if (!IsValidChildType(newChild.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -1507,15 +1519,19 @@ public virtual void PrependChild(string newChild) PrependChild(reader); } - public virtual void PrependChild(XmlReader newChild!!) + public virtual void PrependChild(XmlReader newChild) { + ArgumentNullException.ThrowIfNull(newChild); + XmlWriter writer = PrependChild(); BuildSubtree(newChild, writer); writer.Close(); } - public virtual void PrependChild(XPathNavigator newChild!!) + public virtual void PrependChild(XPathNavigator newChild) { + ArgumentNullException.ThrowIfNull(newChild); + if (!IsValidChildType(newChild.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -1530,15 +1546,19 @@ public virtual void InsertBefore(string newSibling) InsertBefore(reader); } - public virtual void InsertBefore(XmlReader newSibling!!) + public virtual void InsertBefore(XmlReader newSibling) { + ArgumentNullException.ThrowIfNull(newSibling); + XmlWriter writer = InsertBefore(); BuildSubtree(newSibling, writer); writer.Close(); } - public virtual void InsertBefore(XPathNavigator newSibling!!) + public virtual void InsertBefore(XPathNavigator newSibling) { + ArgumentNullException.ThrowIfNull(newSibling); + if (!IsValidSiblingType(newSibling.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -1553,15 +1573,19 @@ public virtual void InsertAfter(string newSibling) InsertAfter(reader); } - public virtual void InsertAfter(XmlReader newSibling!!) + public virtual void InsertAfter(XmlReader newSibling) { + ArgumentNullException.ThrowIfNull(newSibling); + XmlWriter writer = InsertAfter(); BuildSubtree(newSibling, writer); writer.Close(); } - public virtual void InsertAfter(XPathNavigator newSibling!!) + public virtual void InsertAfter(XPathNavigator newSibling) { + ArgumentNullException.ThrowIfNull(newSibling); + if (!IsValidSiblingType(newSibling.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -2017,8 +2041,10 @@ private XmlReader CreateReader() return XPathNavigatorReader.Create(this); } - private XmlReader CreateContextReader(string xml!!, bool fromCurrentNode) + private XmlReader CreateContextReader(string xml, bool fromCurrentNode) { + ArgumentNullException.ThrowIfNull(xml); + // We have to set the namespace context for the reader. XPathNavigator editor = CreateNavigator(); // scope starts from parent. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs index cc155b51536a75..5fcd79f696dd03 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs @@ -20,8 +20,10 @@ bool IEqualityComparer.Equals(object? obj1, object? obj2) return false; } - int IEqualityComparer.GetHashCode(object obj!!) + int IEqualityComparer.GetHashCode(object obj) { + ArgumentNullException.ThrowIfNull(obj); + int hashCode; XPathNavigator? nav; XPathDocumentNavigator? xpdocNav; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs index 152e317ca40757..03c1a02fea5a93 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs @@ -455,8 +455,10 @@ public override int AttributeCount return null; } - public override string? GetAttribute(string localName!!, string? namespaceURI) + public override string? GetAttribute(string localName, string? namespaceURI) { + ArgumentNullException.ThrowIfNull(localName); + // reader allows calling GetAttribute, even when positioned inside attributes XPathNavigator nav = _nav; switch (nav.NodeType) @@ -552,8 +554,10 @@ public override string GetAttribute(int index) } - public override bool MoveToAttribute(string localName!!, string? namespaceName) + public override bool MoveToAttribute(string localName, string? namespaceName) { + ArgumentNullException.ThrowIfNull(localName); + int depth; XPathNavigator? nav = GetElemNav(out depth); if (null != nav) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index f6b6fe20580a29..16aa654e45b1d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -312,13 +312,17 @@ internal static byte[] FromBinHexString(string s) return FromBinHexString(s, true); } - internal static byte[] FromBinHexString(string s!!, bool allowOddCount) + internal static byte[] FromBinHexString(string s, bool allowOddCount) { + ArgumentNullException.ThrowIfNull(s); + return BinHexDecoder.Decode(s.AsSpan(), allowOddCount); } - internal static string ToBinHexString(byte[] inArray!!) + internal static string ToBinHexString(byte[] inArray) { + ArgumentNullException.ThrowIfNull(inArray); + return BinHexEncoder.Encode(inArray, 0, inArray.Length); } @@ -328,8 +332,10 @@ internal static string ToBinHexString(byte[] inArray!!) /// /// /// - public static string VerifyName(string name!!) + public static string VerifyName(string name) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); @@ -389,8 +395,10 @@ public static string VerifyNCName(string name) return VerifyNCName(name, ExceptionType.XmlException); } - internal static string VerifyNCName(string name!!, ExceptionType exceptionType) + internal static string VerifyNCName(string name, ExceptionType exceptionType) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); @@ -462,8 +470,10 @@ public static string VerifyNMTOKEN(string name) return VerifyNMTOKEN(name, ExceptionType.XmlException); } - internal static string VerifyNMTOKEN(string name!!, ExceptionType exceptionType) + internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); @@ -507,16 +517,19 @@ internal static string VerifyNMTOKEN(string name!!, ExceptionType exceptionType) // Verification method for XML characters as defined in XML spec production [2] Char. // Throws XmlException if invalid character is found, otherwise returns the input string. - public static string VerifyXmlChars(string content!!) + public static string VerifyXmlChars(string content) { + ArgumentNullException.ThrowIfNull(content); + VerifyCharData(content, ExceptionType.XmlException); return content; } // Verification method for XML public ID characters as defined in XML spec production [13] PubidChar. // Throws XmlException if invalid character is found, otherwise returns the input string. - public static string VerifyPublicId(string publicId!!) + public static string VerifyPublicId(string publicId) { + ArgumentNullException.ThrowIfNull(publicId); // returns the position of invalid character or -1 int pos = XmlCharType.IsPublicId(publicId); @@ -530,8 +543,9 @@ public static string VerifyPublicId(string publicId!!) // Verification method for XML whitespace characters as defined in XML spec production [3] S. // Throws XmlException if invalid character is found, otherwise returns the input string. - public static string VerifyWhitespace(string content!!) + public static string VerifyWhitespace(string content) { + ArgumentNullException.ThrowIfNull(content); // returns the position of invalid character or -1 int pos = XmlCharType.IsOnlyWhitespaceWithPos(content); @@ -781,8 +795,10 @@ public static bool ToBoolean(string s) return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } - public static char ToChar(string s!!) + public static char ToChar(string s) { + ArgumentNullException.ThrowIfNull(s); + if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); @@ -1235,20 +1251,26 @@ public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTim return dt; } - public static DateTimeOffset ToDateTimeOffset(string s!!) + public static DateTimeOffset ToDateTimeOffset(string s) { + ArgumentNullException.ThrowIfNull(s); + XsdDateTime xsdDateTime = new XsdDateTime(s, XsdDateTimeFlags.AllXsd); DateTimeOffset dateTimeOffset = (DateTimeOffset)xsdDateTime; return dateTimeOffset; } - public static DateTimeOffset ToDateTimeOffset(string s!!, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) + public static DateTimeOffset ToDateTimeOffset(string s, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string format) { + ArgumentNullException.ThrowIfNull(s); + return DateTimeOffset.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } - public static DateTimeOffset ToDateTimeOffset(string s!!, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string[] formats) + public static DateTimeOffset ToDateTimeOffset(string s, [StringSyntax(StringSyntaxAttribute.DateTimeFormat)] string[] formats) { + ArgumentNullException.ThrowIfNull(s); + return DateTimeOffset.ParseExact(s, formats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs index 1c30c5ad468b88..ad9e88480e29be 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs @@ -118,8 +118,11 @@ public virtual bool PopScope() return true; } - public virtual void AddNamespace(string prefix!!, [StringSyntax(StringSyntaxAttribute.Uri)] string uri!!) + public virtual void AddNamespace(string prefix, [StringSyntax(StringSyntaxAttribute.Uri)] string uri) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(uri); + Debug.Assert(_nameTable != null); Debug.Assert(_nsdecls != null); prefix = _nameTable.Add(prefix); @@ -182,8 +185,11 @@ public virtual void AddNamespace(string prefix!!, [StringSyntax(StringSyntaxAttr } } - public virtual void RemoveNamespace(string prefix!!, [StringSyntax(StringSyntaxAttribute.Uri)] string uri!!) + public virtual void RemoveNamespace(string prefix, [StringSyntax(StringSyntaxAttribute.Uri)] string uri) { + ArgumentNullException.ThrowIfNull(prefix); + ArgumentNullException.ThrowIfNull(uri); + Debug.Assert(_nsdecls != null); int declIndex = LookupNamespaceDecl(prefix); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs index ef2873825a7c54..3385ac614c3ee0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs @@ -71,8 +71,10 @@ public virtual ICredentials Credentials set { } } - public virtual bool SupportsType(Uri absoluteUri!!, Type? type) + public virtual bool SupportsType(Uri absoluteUri, Type? type) { + ArgumentNullException.ThrowIfNull(absoluteUri); + if (type == null || type == typeof(Stream)) { return true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs index 58eb5e550843b9..a969743d0feea8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs @@ -35,8 +35,10 @@ public CompilerErrorCollection() { } public int Add(CompilerError value) => List.Add(value); - public void AddRange(CompilerError[] value!!) + public void AddRange(CompilerError[] value) { + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; i < value.Length; i++) { this.Add(value[i]); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs index 220693b894fc9b..4c23f1755ce65f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NavigatorInput.cs @@ -204,8 +204,11 @@ internal bool MoveToNextNamespace() // // Constructor // - internal NavigatorInput(XPathNavigator navigator!!, string baseUri!!, InputScope? rootScope) + internal NavigatorInput(XPathNavigator navigator, string baseUri, InputScope? rootScope) { + ArgumentNullException.ThrowIfNull(navigator); + ArgumentNullException.ThrowIfNull(baseUri); + Debug.Assert(navigator.NameTable != null); _Next = null; _Href = baseUri; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs index 559a2a169f8f8f..2766d0f86e170c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOnlyOutput.cs @@ -24,14 +24,18 @@ public TextWriter Writer // Constructor // - internal TextOnlyOutput(Processor processor, Stream stream!!) + internal TextOnlyOutput(Processor processor, Stream stream) { + ArgumentNullException.ThrowIfNull(stream); + _processor = processor; _writer = new StreamWriter(stream, Output.Encoding); } - internal TextOnlyOutput(Processor processor, TextWriter writer!!) + internal TextOnlyOutput(Processor processor, TextWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + _processor = processor; _writer = writer; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs index e32732fe30c8e5..40d9da3fda7266 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TextOutput.cs @@ -13,16 +13,20 @@ internal sealed class TextOutput : SequentialOutput { private TextWriter _writer; - internal TextOutput(Processor processor, Stream stream!!) + internal TextOutput(Processor processor, Stream stream) : base(processor) { + ArgumentNullException.ThrowIfNull(stream); + this.encoding = processor.Output.Encoding; _writer = new StreamWriter(stream, this.encoding); } - internal TextOutput(Processor processor, TextWriter writer!!) + internal TextOutput(Processor processor, TextWriter writer) : base(processor) { + ArgumentNullException.ThrowIfNull(writer); + this.encoding = writer.Encoding; _writer = writer; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs index 2db4ecb841b4bc..b274bf67d148b7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WriterOutput.cs @@ -11,8 +11,10 @@ internal sealed class WriterOutput : IRecordOutput private XmlWriter _writer; private readonly Processor _processor; - internal WriterOutput(Processor processor, XmlWriter writer!!) + internal WriterOutput(Processor processor, XmlWriter writer) { + ArgumentNullException.ThrowIfNull(writer); + _writer = writer; _processor = processor; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs index 1694851515ba8e..7254705d6eed63 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs @@ -123,8 +123,10 @@ public void Load(string stylesheetUri, XsltSettings? settings, XmlResolver? styl LoadInternal(stylesheetUri, settings, stylesheetResolver); } - private void LoadInternal(object stylesheet!!, XsltSettings? settings, XmlResolver? stylesheetResolver) + private void LoadInternal(object stylesheet, XsltSettings? settings, XmlResolver? stylesheetResolver) { + ArgumentNullException.ThrowIfNull(stylesheet); + settings ??= XsltSettings.Default; CompileXsltToQil(stylesheet, settings, stylesheetResolver); CompilerError? error = GetFirstError(); @@ -233,24 +235,36 @@ public void Load(MethodInfo executeMethod, byte[] queryData, Type[]? earlyBoundT // Transform methods which take an IXPathNavigable //------------------------------------------------ - public void Transform(IXPathNavigable input!!, XmlWriter results!!) + public void Transform(IXPathNavigable input, XmlWriter results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + Transform(input, null, results, CreateDefaultResolver()); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, XmlWriter results!!) + public void Transform(IXPathNavigable input, XsltArgumentList? arguments, XmlWriter results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + Transform(input, arguments, results, CreateDefaultResolver()); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, TextWriter results!!) + public void Transform(IXPathNavigable input, XsltArgumentList? arguments, TextWriter results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(input, arguments, writer, CreateDefaultResolver()); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, Stream results!!) + public void Transform(IXPathNavigable input, XsltArgumentList? arguments, Stream results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(input, arguments, writer, CreateDefaultResolver()); } @@ -259,24 +273,36 @@ public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, Stre // Transform methods which take an XmlReader //------------------------------------------------ - public void Transform(XmlReader input!!, XmlWriter results!!) + public void Transform(XmlReader input, XmlWriter results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + Transform(input, null, results, CreateDefaultResolver()); } - public void Transform(XmlReader input!!, XsltArgumentList? arguments, XmlWriter results!!) + public void Transform(XmlReader input, XsltArgumentList? arguments, XmlWriter results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + Transform(input, arguments, results, CreateDefaultResolver()); } - public void Transform(XmlReader input!!, XsltArgumentList? arguments, TextWriter results!!) + public void Transform(XmlReader input, XsltArgumentList? arguments, TextWriter results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(input, arguments, writer, CreateDefaultResolver()); } - public void Transform(XmlReader input!!, XsltArgumentList? arguments, Stream results!!) + public void Transform(XmlReader input, XsltArgumentList? arguments, Stream results) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(input, arguments, writer, CreateDefaultResolver()); } @@ -288,34 +314,49 @@ public void Transform(XmlReader input!!, XsltArgumentList? arguments, Stream res // suppress the message. //------------------------------------------------ - public void Transform(string inputUri!!, XmlWriter results!!) + public void Transform(string inputUri, XmlWriter results) { + ArgumentNullException.ThrowIfNull(inputUri); + ArgumentNullException.ThrowIfNull(results); + using XmlReader reader = XmlReader.Create(inputUri); Transform(reader, null, results, CreateDefaultResolver()); } - public void Transform(string inputUri!!, XsltArgumentList? arguments, XmlWriter results!!) + public void Transform(string inputUri, XsltArgumentList? arguments, XmlWriter results) { + ArgumentNullException.ThrowIfNull(inputUri); + ArgumentNullException.ThrowIfNull(results); + using XmlReader reader = XmlReader.Create(inputUri); Transform(reader, arguments, results, CreateDefaultResolver()); } - public void Transform(string inputUri!!, XsltArgumentList? arguments, TextWriter results!!) + public void Transform(string inputUri, XsltArgumentList? arguments, TextWriter results) { + ArgumentNullException.ThrowIfNull(inputUri); + ArgumentNullException.ThrowIfNull(results); + using XmlReader reader = XmlReader.Create(inputUri); using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(reader, arguments, writer, CreateDefaultResolver()); } - public void Transform(string inputUri!!, XsltArgumentList? arguments, Stream results!!) + public void Transform(string inputUri, XsltArgumentList? arguments, Stream results) { + ArgumentNullException.ThrowIfNull(inputUri); + ArgumentNullException.ThrowIfNull(results); + using XmlReader reader = XmlReader.Create(inputUri); using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(reader, arguments, writer, CreateDefaultResolver()); } - public void Transform(string inputUri!!, string resultsFile!!) + public void Transform(string inputUri, string resultsFile) { + ArgumentNullException.ThrowIfNull(inputUri); + ArgumentNullException.ThrowIfNull(resultsFile); + // SQLBUDT 276415: Prevent wiping out the content of the input file if the output file is the same using XmlReader reader = XmlReader.Create(inputUri); using XmlWriter writer = XmlWriter.Create(resultsFile, OutputSettings); @@ -328,16 +369,22 @@ public void Transform(string inputUri!!, string resultsFile!!) // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. - public void Transform(XmlReader input!!, XsltArgumentList? arguments, XmlWriter results!!, XmlResolver? documentResolver) + public void Transform(XmlReader input, XsltArgumentList? arguments, XmlWriter results, XmlResolver? documentResolver) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + CheckCommand(); _command.Execute(input, documentResolver, arguments, results); } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. - public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, XmlWriter results!!, XmlResolver? documentResolver) + public void Transform(IXPathNavigable input, XsltArgumentList? arguments, XmlWriter results, XmlResolver? documentResolver) { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(results); + CheckCommand(); _command.Execute(input.CreateNavigator()!, documentResolver, arguments, results); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs index 8c9f755f683cd2..a474d6239402ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslTransform.cs @@ -51,8 +51,10 @@ public void Load(XmlReader stylesheet) { Load(stylesheet, CreateDefaultResolver()); } - public void Load(XmlReader stylesheet!!, XmlResolver? resolver) + public void Load(XmlReader stylesheet, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(stylesheet); + Load(new XPathDocument(stylesheet, XmlSpace.Preserve), resolver); } @@ -60,18 +62,24 @@ public void Load(IXPathNavigable stylesheet) { Load(stylesheet, CreateDefaultResolver()); } - public void Load(IXPathNavigable stylesheet!!, XmlResolver? resolver) + public void Load(IXPathNavigable stylesheet, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(stylesheet); + Load(stylesheet.CreateNavigator()!, resolver); } - public void Load(XPathNavigator stylesheet!!) + public void Load(XPathNavigator stylesheet) { + ArgumentNullException.ThrowIfNull(stylesheet); + Load(stylesheet, CreateDefaultResolver()); } - public void Load(XPathNavigator stylesheet!!, XmlResolver? resolver) + public void Load(XPathNavigator stylesheet, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(stylesheet); + Compile(stylesheet, resolver); } @@ -154,42 +162,58 @@ public void Transform(XPathNavigator input, XsltArgumentList? args, TextWriter o processor.Execute(output); } - public XmlReader Transform(IXPathNavigable input!!, XsltArgumentList? args, XmlResolver? resolver) + public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(input); + return Transform(input.CreateNavigator()!, args, resolver); } - public XmlReader Transform(IXPathNavigable input!!, XsltArgumentList? args) + public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args) { + ArgumentNullException.ThrowIfNull(input); + return Transform(input.CreateNavigator()!, args, _DocumentResolver); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? args, TextWriter output, XmlResolver? resolver) + public void Transform(IXPathNavigable input, XsltArgumentList? args, TextWriter output, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(input); + Transform(input.CreateNavigator()!, args, output, resolver); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? args, TextWriter output) + public void Transform(IXPathNavigable input, XsltArgumentList? args, TextWriter output) { + ArgumentNullException.ThrowIfNull(input); + Transform(input.CreateNavigator()!, args, output, _DocumentResolver); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? args, Stream output, XmlResolver? resolver) + public void Transform(IXPathNavigable input, XsltArgumentList? args, Stream output, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(input); + Transform(input.CreateNavigator()!, args, output, resolver); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? args, Stream output) + public void Transform(IXPathNavigable input, XsltArgumentList? args, Stream output) { + ArgumentNullException.ThrowIfNull(input); + Transform(input.CreateNavigator()!, args, output, _DocumentResolver); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? args, XmlWriter output, XmlResolver? resolver) + public void Transform(IXPathNavigable input, XsltArgumentList? args, XmlWriter output, XmlResolver? resolver) { + ArgumentNullException.ThrowIfNull(input); + Transform(input.CreateNavigator()!, args, output, resolver); } - public void Transform(IXPathNavigable input!!, XsltArgumentList? args, XmlWriter output) + public void Transform(IXPathNavigable input, XsltArgumentList? args, XmlWriter output) { + ArgumentNullException.ThrowIfNull(input); + Transform(input.CreateNavigator()!, args, output, _DocumentResolver); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs index d3b08c776ded0d..c7d303ebddf3a1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltArgumentList.cs @@ -38,16 +38,23 @@ public XsltArgumentList() { } return _extensions[namespaceUri]; } - public void AddParam(string name!!, string namespaceUri!!, object parameter!!) + public void AddParam(string name, string namespaceUri, object parameter) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(namespaceUri); + ArgumentNullException.ThrowIfNull(parameter); + XmlQualifiedName qname = new XmlQualifiedName(name, namespaceUri); qname.Verify(); _parameters.Add(qname, parameter); } [RequiresUnreferencedCode(ExtensionObjectWarning)] - public void AddExtensionObject(string namespaceUri!!, object extension!!) + public void AddExtensionObject(string namespaceUri, object extension) { + ArgumentNullException.ThrowIfNull(namespaceUri); + ArgumentNullException.ThrowIfNull(extension); + _extensions.Add(namespaceUri, extension); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs index 8536e4beb1646e..8c94051b44be83 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/CustomReflectionContext.cs @@ -20,19 +20,34 @@ public abstract partial class CustomReflectionContext : ReflectionContext protected CustomReflectionContext() : this(new IdentityReflectionContext()) { } - protected CustomReflectionContext(ReflectionContext source!!) + protected CustomReflectionContext(ReflectionContext source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + SourceContext = source; _projector = new ReflectionContextProjector(this); } - public override Assembly MapAssembly(Assembly assembly!!) + public override Assembly MapAssembly(Assembly assembly) { + if (assembly is null) + { + throw new ArgumentNullException(nameof(assembly)); + } + return _projector.ProjectAssemblyIfNeeded(assembly); } - public override TypeInfo MapType(TypeInfo type!!) + public override TypeInfo MapType(TypeInfo type) { + if (type is null) + { + throw new ArgumentNullException(nameof(type)); + } + return _projector.ProjectTypeIfNeeded(type); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs index dd2b782ac4855d..a719de60a3f789 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualParameter.cs @@ -8,8 +8,17 @@ namespace System.Reflection.Context.Virtual { internal class VirtualParameter : ParameterInfo { - public VirtualParameter(MemberInfo member!!, Type parameterType!!, string? name, int position) + public VirtualParameter(MemberInfo member, Type parameterType, string? name, int position) { + if (member is null) + { + throw new ArgumentNullException(nameof(member)); + } + if (parameterType is null) + { + throw new ArgumentNullException(nameof(parameterType)); + } + Debug.Assert(position >= -1); ClassImpl = parameterType; diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs index badbc3b6f045c1..279bd2947412b2 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Virtual/VirtualPropertyBase.cs @@ -15,8 +15,11 @@ internal abstract partial class VirtualPropertyBase : PropertyInfo private Type? _declaringType; private ParameterInfo[]? _indexedParameters; - protected VirtualPropertyBase(Type propertyType, string name!!, CustomReflectionContext context) + protected VirtualPropertyBase(Type propertyType, string name, CustomReflectionContext context) { + if (name is null) + throw new ArgumentNullException(nameof(name)); + if (name.Length == 0) throw new ArgumentException("", nameof(name)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs index 77a4ee2acbc3c0..c205f5875f9c29 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs @@ -32,7 +32,7 @@ internal static MemoryBlock CreateChecked(byte* buffer, int length) if (buffer == null && length != 0) { - throw new ArgumentNullException(nameof(buffer)); + Throw.ArgumentNull(nameof(buffer)); } return new MemoryBlock(buffer, length); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs index 3235d1c3cc2159..6cde1154c5703c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs @@ -321,8 +321,13 @@ public ImmutableArray ToImmutableArray(int start, int byteCount) /// is null. /// Content is not available, the builder has been linked with another one. - public void WriteContentTo(Stream destination!!) + public void WriteContentTo(Stream destination) { + if (destination is null) + { + Throw.ArgumentNull(nameof(destination)); + } + foreach (var chunk in GetChunks()) { destination.Write(chunk._buffer, 0, chunk.Length); @@ -346,8 +351,13 @@ public void WriteContentTo(ref BlobWriter destination) /// is null. /// Content is not available, the builder has been linked with another one. - public void WriteContentTo(BlobBuilder destination!!) + public void WriteContentTo(BlobBuilder destination) { + if (destination is null) + { + Throw.ArgumentNull(nameof(destination)); + } + foreach (var chunk in GetChunks()) { destination.WriteBytes(chunk._buffer, 0, chunk.Length); @@ -356,8 +366,13 @@ public void WriteContentTo(BlobBuilder destination!!) /// is null. /// Builder is not writable, it has been linked with another one. - public void LinkPrefix(BlobBuilder prefix!!) + public void LinkPrefix(BlobBuilder prefix) { + if (prefix is null) + { + Throw.ArgumentNull(nameof(prefix)); + } + // TODO: consider copying data from right to left while there is space if (!prefix.IsHead || !IsHead) @@ -411,8 +426,13 @@ public void LinkPrefix(BlobBuilder prefix!!) /// is null. /// Builder is not writable, it has been linked with another one. - public void LinkSuffix(BlobBuilder suffix!!) + public void LinkSuffix(BlobBuilder suffix) { + if (suffix is null) + { + Throw.ArgumentNull(nameof(suffix)); + } + // TODO: consider copying data from right to left while there is space if (!IsHead || !suffix.IsHead) @@ -615,8 +635,13 @@ public void WriteBytes(byte value, int byteCount) /// is null. /// is negative. /// Builder is not writable, it has been linked with another one. - public unsafe void WriteBytes(byte* buffer!!, int byteCount) + public unsafe void WriteBytes(byte* buffer, int byteCount) { + if (buffer is null) + { + Throw.ArgumentNull(nameof(buffer)); + } + if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); @@ -652,8 +677,13 @@ private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) /// is negative. /// Builder is not writable, it has been linked with another one. /// Bytes successfully written from the . - public int TryWriteBytes(Stream source!!, int byteCount) + public int TryWriteBytes(Stream source, int byteCount) { + if (source is null) + { + Throw.ArgumentNull(nameof(source)); + } + if (byteCount < 0) { throw new ArgumentOutOfRangeException(nameof(byteCount)); @@ -716,8 +746,13 @@ public void WriteBytes(byte[] buffer) /// is null. /// Range specified by and falls outside of the bounds of the . /// Builder is not writable, it has been linked with another one. - public unsafe void WriteBytes(byte[] buffer!!, int start, int byteCount) + public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) { + if (buffer is null) + { + Throw.ArgumentNull(nameof(buffer)); + } + BlobUtilities.ValidateRange(buffer.Length, start, byteCount, nameof(byteCount)); if (!IsHead) @@ -894,8 +929,13 @@ public void WriteReference(int reference, bool isSmall) /// /// is null. /// Builder is not writable, it has been linked with another one. - public unsafe void WriteUTF16(char[] value!!) + public unsafe void WriteUTF16(char[] value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); @@ -927,8 +967,13 @@ public unsafe void WriteUTF16(char[] value!!) /// /// is null. /// Builder is not writable, it has been linked with another one. - public unsafe void WriteUTF16(string value!!) + public unsafe void WriteUTF16(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + if (!IsHead) { Throw.InvalidOperationBuilderAlreadyLinked(); @@ -980,8 +1025,13 @@ public void WriteSerializedString(string? value) /// The 1 signifies Unicode characters that require handling beyond that normally provided for 8-bit encoding sets. /// /// Builder is not writable, it has been linked with another one. - public void WriteUserString(string value!!) + public void WriteUserString(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); WriteUTF16(value); WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); @@ -996,8 +1046,13 @@ public void WriteUserString(string value!!) /// /// is null. /// Builder is not writable, it has been linked with another one. - public void WriteUTF8(string value!!, bool allowUnpairedSurrogates = true) + public void WriteUTF8(string value, bool allowUnpairedSurrogates = true) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates, prependSize: false); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs index ca4332bfd383a9..653d9e69e61eca 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobContentId.cs @@ -26,8 +26,13 @@ public BlobContentId(ImmutableArray id) { } - public unsafe BlobContentId(byte[] id!!) + public unsafe BlobContentId(byte[] id) { + if (id is null) + { + Throw.ArgumentNull(nameof(id)); + } + if (id.Length != Size) { throw new ArgumentException(SR.Format(SR.UnexpectedArrayLength, Size), nameof(id)); @@ -48,8 +53,13 @@ public static BlobContentId FromHash(ImmutableArray hashCode) return FromHash(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(hashCode)!); } - public static BlobContentId FromHash(byte[] hashCode!!) + public static BlobContentId FromHash(byte[] hashCode) { + if (hashCode is null) + { + Throw.ArgumentNull(nameof(hashCode)); + } + const int minHashSize = 20; if (hashCode.Length < minHashSize) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs index 0e088355e28958..dc63a0de0a557f 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriter.cs @@ -140,8 +140,13 @@ public void WriteBytes(byte value, int byteCount) /// is null. /// is negative. - public unsafe void WriteBytes(byte* buffer!!, int byteCount) + public unsafe void WriteBytes(byte* buffer, int byteCount) { + if (buffer is null) + { + Throw.ArgumentNull(nameof(buffer)); + } + if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); @@ -157,15 +162,25 @@ private unsafe void WriteBytesUnchecked(byte* buffer, int byteCount) } /// is null. - public void WriteBytes(BlobBuilder source!!) + public void WriteBytes(BlobBuilder source) { + if (source is null) + { + Throw.ArgumentNull(nameof(source)); + } + source.WriteContentTo(ref this); } /// is null. /// is negative. - public int WriteBytes(Stream source!!, int byteCount) + public int WriteBytes(Stream source, int byteCount) { + if (source is null) + { + Throw.ArgumentNull(nameof(source)); + } + if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); @@ -198,8 +213,13 @@ public unsafe void WriteBytes(byte[] buffer) /// is null. /// Range specified by and falls outside of the bounds of the . - public unsafe void WriteBytes(byte[] buffer!!, int start, int byteCount) + public unsafe void WriteBytes(byte[] buffer, int start, int byteCount) { + if (buffer is null) + { + Throw.ArgumentNull(nameof(buffer)); + } + BlobUtilities.ValidateRange(buffer.Length, start, byteCount, nameof(byteCount)); // an empty array has no element pointer: @@ -349,8 +369,13 @@ public void WriteReference(int reference, bool isSmall) /// Writes UTF16 (little-endian) encoded string at the current position. /// /// is null. - public void WriteUTF16(char[] value!!) + public void WriteUTF16(char[] value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + if (value.Length == 0) { return; @@ -376,8 +401,13 @@ public void WriteUTF16(char[] value!!) /// Writes UTF16 (little-endian) encoded string at the current position. /// /// is null. - public void WriteUTF16(string value!!) + public void WriteUTF16(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + if (BitConverter.IsLittleEndian) { fixed (char* ptr = value) @@ -424,8 +454,13 @@ public void WriteSerializedString(string? str) /// The 1 signifies Unicode characters that require handling beyond that normally provided for 8-bit encoding sets. /// /// Builder is not writable, it has been linked with another one. - public void WriteUserString(string value!!) + public void WriteUserString(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); WriteUTF16(value); WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); @@ -435,8 +470,13 @@ public void WriteUserString(string value!!) /// Writes UTF8 encoded string at the current position. /// /// is null. - public void WriteUTF8(string value!!, bool allowUnpairedSurrogates) + public void WriteUTF8(string value, bool allowUnpairedSurrogates) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + WriteUTF8(value, 0, value.Length, allowUnpairedSurrogates, prependSize: false); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs index 5e662461018652..bd4994572b94ec 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/Encoding/BlobEncoders.cs @@ -12,8 +12,13 @@ public readonly struct BlobEncoder { public BlobBuilder Builder { get; } - public BlobEncoder(BlobBuilder builder!!) + public BlobEncoder(BlobBuilder builder) { + if (builder is null) + { + Throw.ArgumentNull(nameof(builder)); + } + Builder = builder; } @@ -109,8 +114,17 @@ public void CustomAttributeSignature(out FixedArgumentsEncoder fixedArguments, o /// Called first, to encode fixed arguments. /// Called second, to encode named arguments. /// or is null. - public void CustomAttributeSignature(Action fixedArguments!!, Action namedArguments!!) + public void CustomAttributeSignature(Action fixedArguments, Action namedArguments) { + if (fixedArguments is null) + { + Throw.ArgumentNull(nameof(fixedArguments)); + } + if (namedArguments is null) + { + Throw.ArgumentNull(nameof(namedArguments)); + } + FixedArgumentsEncoder fixedArgumentsEncoder; CustomAttributeNamedArgumentsEncoder namedArgumentsEncoder; CustomAttributeSignature(out fixedArgumentsEncoder, out namedArgumentsEncoder); @@ -220,8 +234,17 @@ public void Parameters(int parameterCount, out ReturnTypeEncoder returnType, out /// Called first, to encode the return type. /// Called second, to encode the actual parameters. /// or is null. - public void Parameters(int parameterCount, Action returnType!!, Action parameters!!) + public void Parameters(int parameterCount, Action returnType, Action parameters) { + if (returnType is null) + { + Throw.ArgumentNull(nameof(returnType)); + } + if (parameters is null) + { + Throw.ArgumentNull(nameof(parameters)); + } + ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; Parameters(parameterCount, out returnTypeEncoder, out parametersEncoder); @@ -319,8 +342,13 @@ public PermissionSetEncoder(BlobBuilder builder) Builder = builder; } - public PermissionSetEncoder AddPermission(string typeName!!, ImmutableArray encodedArguments) + public PermissionSetEncoder AddPermission(string typeName, ImmutableArray encodedArguments) { + if (typeName is null) + { + Throw.ArgumentNull(nameof(typeName)); + } + if (encodedArguments.IsDefault) { Throw.ArgumentNull(nameof(encodedArguments)); @@ -337,8 +365,17 @@ public PermissionSetEncoder AddPermission(string typeName!!, ImmutableArray BlobWriterImpl.MaxCompressedIntegerValue) { Throw.BlobTooLarge(nameof(encodedArguments)); @@ -413,8 +450,17 @@ public void TaggedVector(out CustomAttributeArrayTypeEncoder arrayType, out Vect /// Called first, to encode the type of the vector. /// Called second, to encode the items of the vector. /// or is null. - public void TaggedVector(Action arrayType!!, Action vector!!) + public void TaggedVector(Action arrayType, Action vector) { + if (arrayType is null) + { + Throw.ArgumentNull(nameof(arrayType)); + } + if (vector is null) + { + Throw.ArgumentNull(nameof(vector)); + } + CustomAttributeArrayTypeEncoder arrayTypeEncoder; VectorEncoder vectorEncoder; TaggedVector(out arrayTypeEncoder, out vectorEncoder); @@ -449,8 +495,17 @@ public void TaggedScalar(out CustomAttributeElementTypeEncoder type, out ScalarE /// Called first, to encode the type of the literal. /// Called second, to encode the value of the literal. /// or is null. - public void TaggedScalar(Action type!!, Action scalar!!) + public void TaggedScalar(Action type, Action scalar) { + if (type is null) + { + Throw.ArgumentNull(nameof(type)); + } + if (scalar is null) + { + Throw.ArgumentNull(nameof(scalar)); + } + CustomAttributeElementTypeEncoder typeEncoder; ScalarEncoder scalarEncoder; TaggedScalar(out typeEncoder, out scalarEncoder); @@ -576,8 +631,13 @@ public NameEncoder(BlobBuilder builder) Builder = builder; } - public void Name(string name!!) + public void Name(string name) { + if (name is null) + { + Throw.ArgumentNull(nameof(name)); + } + if (name.Length == 0) Throw.ArgumentEmptyString(nameof(name)); Builder.WriteSerializedString(name); @@ -638,8 +698,21 @@ public void AddArgument(bool isField, out NamedArgumentTypeEncoder type, out Nam /// Called second, to encode the name of the field or property. /// Called third, to encode the literal value of the argument. /// , or is null. - public void AddArgument(bool isField, Action type!!, Action name!!, Action literal!!) + public void AddArgument(bool isField, Action type, Action name, Action literal) { + if (type is null) + { + Throw.ArgumentNull(nameof(type)); + } + if (name is null) + { + Throw.ArgumentNull(nameof(name)); + } + if (literal is null) + { + Throw.ArgumentNull(nameof(literal)); + } + NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; LiteralEncoder literalEncoder; @@ -756,8 +829,13 @@ public void SystemType() WriteTypeCode(SerializationTypeCode.Type); } - public void Enum(string enumTypeName!!) + public void Enum(string enumTypeName) { + if (enumTypeName is null) + { + Throw.ArgumentNull(nameof(enumTypeName)); + } + if (enumTypeName.Length == 0) Throw.ArgumentEmptyString(nameof(enumTypeName)); WriteTypeCode(SerializationTypeCode.Enum); @@ -856,8 +934,17 @@ public void Array(out SignatureTypeEncoder elementType, out ArrayShapeEncoder ar /// Called first, to encode the type of the element. /// Called second, to encode the shape of the array. /// or is null. - public void Array(Action elementType!!, Action arrayShape!!) + public void Array(Action elementType, Action arrayShape) { + if (elementType is null) + { + Throw.ArgumentNull(nameof(elementType)); + } + if (arrayShape is null) + { + Throw.ArgumentNull(nameof(arrayShape)); + } + SignatureTypeEncoder elementTypeEncoder; ArrayShapeEncoder arrayShapeEncoder; Array(out elementTypeEncoder, out arrayShapeEncoder); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs index 23cc2ac2358c05..602bf71a233068 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs @@ -55,7 +55,7 @@ private MetadataAggregator( { if (baseReader == null) { - throw new ArgumentNullException(nameof(baseReader)); + Throw.ArgumentNull(nameof(baseReader)); } if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0) @@ -75,7 +75,7 @@ private MetadataAggregator( if (baseHeapSizes == null) { - throw new ArgumentNullException(nameof(baseHeapSizes)); + Throw.ArgumentNull(nameof(baseHeapSizes)); } if (baseHeapSizes.Count != MetadataTokens.HeapCount) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs index 796dd46aa17162..89e39aff7c4d1a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs @@ -186,8 +186,13 @@ public void SetCapacity(HeapIndex heap, int byteCount) /// containing the blob. /// Handle to the added or existing blob. /// is null. - public BlobHandle GetOrAddBlob(BlobBuilder value!!) + public BlobHandle GetOrAddBlob(BlobBuilder value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + // TODO: avoid making a copy if the blob exists in the index return GetOrAddBlob(value.ToImmutableArray()); } @@ -198,8 +203,13 @@ public BlobHandle GetOrAddBlob(BlobBuilder value!!) /// Array containing the blob. /// Handle to the added or existing blob. /// is null. - public BlobHandle GetOrAddBlob(byte[] value!!) + public BlobHandle GetOrAddBlob(byte[] value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + // TODO: avoid making a copy if the blob exists in the index return GetOrAddBlob(ImmutableArray.Create(value)); } @@ -291,8 +301,13 @@ public BlobHandle GetOrAddBlobUTF8(string value, bool allowUnpairedSurrogates = /// (see https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#DocumentNameBlob). /// /// is null. - public BlobHandle GetOrAddDocumentName(string value!!) + public BlobHandle GetOrAddDocumentName(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + char separator = ChooseSeparator(value); var resultBuilder = PooledBlobBuilder.GetInstance(); @@ -409,8 +424,13 @@ private GuidHandle GetNewGuidHandle() /// Array containing the blob. /// Handle to the added or existing blob. /// is null. - public StringHandle GetOrAddString(string value!!) + public StringHandle GetOrAddString(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + StringHandle handle; if (value.Length == 0) { @@ -460,8 +480,13 @@ public ReservedBlob ReserveUserString(int length) /// /// The remaining space on the heap is too small to fit the string. /// is null. - public UserStringHandle GetOrAddUserString(string value!!) + public UserStringHandle GetOrAddUserString(string value) { + if (value is null) + { + Throw.ArgumentNull(nameof(value)); + } + UserStringHandle handle; if (!_userStrings.TryGetValue(value, out handle)) { diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs index 04062e9316aeaa..93baf043f25982 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs @@ -386,12 +386,17 @@ public ModuleDefinitionHandle AddModule( public AssemblyDefinitionHandle AddAssembly( StringHandle name, - Version version!!, + Version version, StringHandle culture, BlobHandle publicKey, AssemblyFlags flags, AssemblyHashAlgorithm hashAlgorithm) { + if (version is null) + { + Throw.ArgumentNull(nameof(version)); + } + if (_assemblyRow.HasValue) { Throw.InvalidOperation(SR.AssemblyAlreadyAdded); @@ -412,12 +417,17 @@ public AssemblyDefinitionHandle AddAssembly( public AssemblyReferenceHandle AddAssemblyReference( StringHandle name, - Version version!!, + Version version, StringHandle culture, BlobHandle publicKeyOrToken, AssemblyFlags flags, BlobHandle hashValue) { + if (version is null) + { + Throw.ArgumentNull(nameof(version)); + } + _assemblyRefTable.Add(new AssemblyRefTableRow { Name = name, diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs index 031524a9cd4e7b..62fbf3c8942bea 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataReaderExtensions.cs @@ -17,8 +17,13 @@ public static class MetadataReaderExtensions /// /// is null. /// is not a valid table index. - public static int GetTableRowCount(this MetadataReader reader!!, TableIndex tableIndex) + public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + if ((int)tableIndex >= MetadataTokens.TableCount) { Throw.TableIndexOutOfRange(); @@ -32,8 +37,13 @@ public static int GetTableRowCount(this MetadataReader reader!!, TableIndex tabl /// /// is null. /// is not a valid table index. - public static int GetTableRowSize(this MetadataReader reader!!, TableIndex tableIndex) + public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return tableIndex switch { TableIndex.Module => reader.ModuleTable.RowSize, @@ -101,8 +111,13 @@ public static int GetTableRowSize(this MetadataReader reader!!, TableIndex table /// /// is null. /// is not a valid table index. - public static unsafe int GetTableMetadataOffset(this MetadataReader reader!!, TableIndex tableIndex) + public static unsafe int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return (int)(reader.GetTableMetadataBlock(tableIndex).Pointer - reader.Block.Pointer); } @@ -177,8 +192,13 @@ private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, Tab /// /// is null. /// is not a valid heap index. - public static int GetHeapSize(this MetadataReader reader!!, HeapIndex heapIndex) + public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return reader.GetMetadataBlock(heapIndex).Length; } @@ -187,8 +207,13 @@ public static int GetHeapSize(this MetadataReader reader!!, HeapIndex heapIndex) /// /// is null. /// is not a valid heap index. - public static unsafe int GetHeapMetadataOffset(this MetadataReader reader!!, HeapIndex heapIndex) + public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return (int)(reader.GetMetadataBlock(heapIndex).Pointer - reader.Block.Pointer); } @@ -215,8 +240,13 @@ private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapInde /// Returns the a handle to the UserString that follows the given one in the UserString heap or a nil handle if it is the last one. /// /// is null. - public static UserStringHandle GetNextHandle(this MetadataReader reader!!, UserStringHandle handle) + public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return reader.UserStringHeap.GetNextHandle(handle); } @@ -224,8 +254,13 @@ public static UserStringHandle GetNextHandle(this MetadataReader reader!!, UserS /// Returns the a handle to the Blob that follows the given one in the Blob heap or a nil handle if it is the last one. /// /// is null. - public static BlobHandle GetNextHandle(this MetadataReader reader!!, BlobHandle handle) + public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return reader.BlobHeap.GetNextHandle(handle); } @@ -233,8 +268,13 @@ public static BlobHandle GetNextHandle(this MetadataReader reader!!, BlobHandle /// Returns the a handle to the String that follows the given one in the String heap or a nil handle if it is the last one. /// /// is null. - public static StringHandle GetNextHandle(this MetadataReader reader!!, StringHandle handle) + public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + return reader.StringHeap.GetNextHandle(handle); } @@ -242,13 +282,23 @@ public static StringHandle GetNextHandle(this MetadataReader reader!!, StringHan /// Enumerates entries of EnC log. /// /// is null. - public static IEnumerable GetEditAndContinueLogEntries(this MetadataReader reader!!) + public static IEnumerable GetEditAndContinueLogEntries(this MetadataReader reader) { - for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++) + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + + return Core(reader); + + static IEnumerable Core(MetadataReader reader) { - yield return new EditAndContinueLogEntry( - new EntityHandle(reader.EncLogTable.GetToken(rid)), - reader.EncLogTable.GetFuncCode(rid)); + for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++) + { + yield return new EditAndContinueLogEntry( + new EntityHandle(reader.EncLogTable.GetToken(rid)), + reader.EncLogTable.GetFuncCode(rid)); + } } } @@ -256,11 +306,21 @@ public static IEnumerable GetEditAndContinueLogEntries( /// Enumerates entries of EnC map. /// /// is null. - public static IEnumerable GetEditAndContinueMapEntries(this MetadataReader reader!!) + public static IEnumerable GetEditAndContinueMapEntries(this MetadataReader reader) { - for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++) + if (reader is null) { - yield return new EntityHandle(reader.EncMapTable.GetToken(rid)); + Throw.ArgumentNull(nameof(reader)); + } + + return Core(reader); + + static IEnumerable Core(MetadataReader reader) + { + for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++) + { + yield return new EntityHandle(reader.EncMapTable.GetToken(rid)); + } } } @@ -271,11 +331,21 @@ public static IEnumerable GetEditAndContinueMapEntries(this Metada /// The resulting sequence corresponds exactly to entries in PropertyMap table, /// i.e. n-th returned is stored in n-th row of PropertyMap. /// - public static IEnumerable GetTypesWithProperties(this MetadataReader reader!!) + public static IEnumerable GetTypesWithProperties(this MetadataReader reader) { - for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++) + if (reader is null) { - yield return reader.PropertyMapTable.GetParentType(rid); + Throw.ArgumentNull(nameof(reader)); + } + + return Core(reader); + + static IEnumerable Core(MetadataReader reader) + { + for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++) + { + yield return reader.PropertyMapTable.GetParentType(rid); + } } } @@ -286,19 +356,34 @@ public static IEnumerable GetTypesWithProperties(this Meta /// The resulting sequence corresponds exactly to entries in EventMap table, /// i.e. n-th returned is stored in n-th row of EventMap. /// - public static IEnumerable GetTypesWithEvents(this MetadataReader reader!!) + public static IEnumerable GetTypesWithEvents(this MetadataReader reader) { - for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++) + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + + return Core(reader); + + static IEnumerable Core(MetadataReader reader) { - yield return reader.EventMapTable.GetParentType(rid); + for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++) + { + yield return reader.EventMapTable.GetParentType(rid); + } } } /// /// Given a type handle and a raw type kind found in a signature blob determines whether the target type is a value type or a reference type. /// - public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader!!, EntityHandle typeHandle, byte rawTypeKind) + public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader, EntityHandle typeHandle, byte rawTypeKind) { + if (reader is null) + { + Throw.ArgumentNull(nameof(reader)); + } + var typeKind = (SignatureTypeKind)rawTypeKind; switch (typeKind) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs index 5a7b947159fcc9..bb6338dd853b28 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataRootBuilder.cs @@ -51,8 +51,13 @@ public sealed class MetadataRootBuilder /// /// is null. /// is too long (the number of bytes when UTF8-encoded must be less than 255). - public MetadataRootBuilder(MetadataBuilder tablesAndHeaps!!, string? metadataVersion = null, bool suppressValidation = false) + public MetadataRootBuilder(MetadataBuilder tablesAndHeaps, string? metadataVersion = null, bool suppressValidation = false) { + if (tablesAndHeaps is null) + { + Throw.ArgumentNull(nameof(tablesAndHeaps)); + } + Debug.Assert(BlobUtilities.GetUTF8ByteCount(DefaultMetadataVersionString) == DefaultMetadataVersionString.Length); int metadataVersionByteCount = metadataVersion != null ? BlobUtilities.GetUTF8ByteCount(metadataVersion) : DefaultMetadataVersionString.Length; @@ -89,8 +94,13 @@ public MetadataRootBuilder(MetadataBuilder tablesAndHeaps!!, string? metadataVer /// /// A metadata table is not ordered as required by the specification and is false. /// - public void Serialize(BlobBuilder builder!!, int methodBodyStreamRva, int mappedFieldDataStreamRva) + public void Serialize(BlobBuilder builder, int methodBodyStreamRva, int mappedFieldDataStreamRva) { + if (builder is null) + { + Throw.ArgumentNull(nameof(builder)); + } + if (methodBodyStreamRva < 0) { Throw.ArgumentOutOfRange(nameof(methodBodyStreamRva)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs index 0fb6349de43df0..dfd862daee2340 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/PortablePdbBuilder.cs @@ -45,11 +45,16 @@ public sealed class PortablePdbBuilder /// /// or is null. public PortablePdbBuilder( - MetadataBuilder tablesAndHeaps!!, + MetadataBuilder tablesAndHeaps, ImmutableArray typeSystemRowCounts, MethodDefinitionHandle entryPoint, Func, BlobContentId>? idProvider = null) { + if (tablesAndHeaps is null) + { + Throw.ArgumentNull(nameof(tablesAndHeaps)); + } + ValidateTypeSystemRowCounts(typeSystemRowCounts); _builder = tablesAndHeaps; @@ -117,8 +122,13 @@ private void SerializeStandalonePdbStream(BlobBuilder builder) /// Builder to write to. /// The id of the serialized content. /// is null. - public BlobContentId Serialize(BlobBuilder builder!!) + public BlobContentId Serialize(BlobBuilder builder) { + if (builder is null) + { + Throw.ArgumentNull(nameof(builder)); + } + // header: MetadataBuilder.SerializeMetadataHeader(builder, MetadataVersion, _serializedMetadata.Sizes); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs index 8cdf85ab43e43f..e957921c79d542 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs @@ -27,10 +27,15 @@ public readonly struct SignatureDecoder /// Additional context needed to resolve generic parameters. /// public SignatureDecoder( - ISignatureTypeProvider provider!!, + ISignatureTypeProvider provider, MetadataReader metadataReader, TGenericContext genericContext) { + if (provider is null) + { + Throw.ArgumentNull(nameof(provider)); + } + _metadataReaderOpt = metadataReader; _provider = provider; _genericContext = genericContext; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs index e2c99399421f94..882ddba2f6c3a0 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs @@ -42,8 +42,13 @@ internal AssemblyName GetAssemblyName(StringHandle nameHandle, Version version, return assemblyName; } - internal static unsafe AssemblyName GetAssemblyName(string assemblyFile!!) + internal static unsafe AssemblyName GetAssemblyName(string assemblyFile) { + if (assemblyFile is null) + { + Throw.ArgumentNull(nameof(assemblyFile)); + } + FileStream? fileStream = null; MemoryMappedFile? mappedFile = null; MemoryMappedViewAccessor? accessor = null; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs index eb2e32d07cffe5..c55b7805d49917 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReaderProvider.cs @@ -68,8 +68,13 @@ private MetadataReaderProvider(MemoryBlockProvider blockProvider) /// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the . /// The content of the blob is not read during the construction of the /// - public static unsafe MetadataReaderProvider FromMetadataImage(byte* start!!, int size) + public static unsafe MetadataReaderProvider FromMetadataImage(byte* start, int size) { + if (start is null) + { + Throw.ArgumentNull(nameof(start)); + } + if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); @@ -100,7 +105,7 @@ public static MetadataReaderProvider FromMetadataImage(ImmutableArray imag { if (image.IsDefault) { - throw new ArgumentNullException(nameof(image)); + Throw.ArgumentNull(nameof(image)); } return new MetadataReaderProvider(new ByteArrayMemoryProvider(image)); @@ -155,8 +160,13 @@ public static MetadataReaderProvider FromMetadataImage(ImmutableArray imag /// doesn't support read and seek operations. /// Size is negative or extends past the end of the stream. /// Error reading from the stream (only when is specified). - public static MetadataReaderProvider FromMetadataStream(Stream stream!!, MetadataStreamOptions options = MetadataStreamOptions.Default, int size = 0) + public static MetadataReaderProvider FromMetadataStream(Stream stream, MetadataStreamOptions options = MetadataStreamOptions.Default, int size = 0) { + if (stream is null) + { + Throw.ArgumentNull(nameof(stream)); + } + if (!stream.CanRead || !stream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(stream)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs index d5e3f7a6acb7d6..73c63f5105987c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataStringDecoder.cs @@ -41,8 +41,13 @@ public class MetadataStringDecoder /// /// To cache and reuse existing strings. Create a derived class and override /// - public MetadataStringDecoder(Encoding encoding!!) + public MetadataStringDecoder(Encoding encoding) { + if (encoding is null) + { + Throw.ArgumentNull(nameof(encoding)); + } + // Non-enforcement of (encoding is UTF8Encoding) here is by design. // // This type is not itself aware of any particular encoding. However, the constructor argument that accepts a diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs index 7f924ed70363c9..0e2c7ca9f69e16 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PEReaderExtensions.cs @@ -21,8 +21,13 @@ public static class PEReaderExtensions /// The body is not found in the metadata or is invalid. /// Section where the method is stored is not available. /// IO error while reading from the underlying stream. - public static MethodBodyBlock GetMethodBody(this PEReader peReader!!, int relativeVirtualAddress) + public static MethodBodyBlock GetMethodBody(this PEReader peReader, int relativeVirtualAddress) { + if (peReader is null) + { + Throw.ArgumentNull(nameof(peReader)); + } + var block = peReader.GetSectionData(relativeVirtualAddress); if (block.Length == 0) { @@ -71,8 +76,13 @@ public static MetadataReader GetMetadataReader(this PEReader peReader, MetadataR /// The encoding of is not . /// The current platform is big-endian. /// IO error while reading from the underlying stream. - public static unsafe MetadataReader GetMetadataReader(this PEReader peReader!!, MetadataReaderOptions options, MetadataStringDecoder? utf8Decoder) + public static unsafe MetadataReader GetMetadataReader(this PEReader peReader, MetadataReaderOptions options, MetadataStringDecoder? utf8Decoder) { + if (peReader is null) + { + Throw.ArgumentNull(nameof(peReader)); + } + var metadata = peReader.GetMetadata(); return new MetadataReader(metadata.Pointer, metadata.Length, options, utf8Decoder, memoryOwner: peReader); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs index 7ba3ba937aecde..66d8d523d50d1b 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.EmbeddedPortablePdb.cs @@ -18,8 +18,13 @@ public sealed partial class DebugDirectoryBuilder /// Version of Portable PDB format (e.g. 0x0100 for 1.0). /// is null. /// is smaller than 0x0100. - public void AddEmbeddedPortablePdbEntry(BlobBuilder debugMetadata!!, ushort portablePdbVersion) + public void AddEmbeddedPortablePdbEntry(BlobBuilder debugMetadata, ushort portablePdbVersion) { + if (debugMetadata is null) + { + Throw.ArgumentNull(nameof(debugMetadata)); + } + if (portablePdbVersion < PortablePdbVersions.MinFormatVersion) { Throw.ArgumentOutOfRange(nameof(portablePdbVersion)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs index 77b5826d30964b..82c3a16bc967d1 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/DebugDirectory/DebugDirectoryBuilder.cs @@ -55,8 +55,13 @@ public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp) /// Entry stamp. /// Data passed to . /// Serializes data to a . - public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp, TData data, Action dataSerializer!!) + public void AddEntry(DebugDirectoryEntryType type, uint version, uint stamp, TData data, Action dataSerializer) { + if (dataSerializer is null) + { + Throw.ArgumentNull(nameof(dataSerializer)); + } + int start = _dataBuilder.Count; dataSerializer(_dataBuilder, data); int dataSize = _dataBuilder.Count - start; @@ -93,11 +98,16 @@ public void AddCodeViewEntry( /// is less than 1. /// is smaller than 0x0100. public void AddCodeViewEntry( - string pdbPath!!, + string pdbPath, BlobContentId pdbContentId, ushort portablePdbVersion, int age) { + if (pdbPath is null) + { + Throw.ArgumentNull(nameof(pdbPath)); + } + if (age < 1) { Throw.ArgumentOutOfRange(nameof(age)); @@ -158,8 +168,13 @@ private static int WriteCodeViewData(BlobBuilder builder, string pdbPath, Guid p /// Checksum. /// or is null. /// or is empty. - public void AddPdbChecksumEntry(string algorithmName!!, ImmutableArray checksum) + public void AddPdbChecksumEntry(string algorithmName, ImmutableArray checksum) { + if (algorithmName is null) + { + Throw.ArgumentNull(nameof(algorithmName)); + } + if (algorithmName.Length == 0) { Throw.ArgumentEmptyString(nameof(algorithmName)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs index ecb424666a4d0e..76195a7ea11b73 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/ManagedPEBuilder.cs @@ -35,9 +35,9 @@ public class ManagedPEBuilder : PEBuilder private Blob _lazyStrongNameSignature; public ManagedPEBuilder( - PEHeaderBuilder header!!, - MetadataRootBuilder metadataRootBuilder!!, - BlobBuilder ilStream!!, + PEHeaderBuilder header, + MetadataRootBuilder metadataRootBuilder, + BlobBuilder ilStream, BlobBuilder? mappedFieldData = null, BlobBuilder? managedResources = null, ResourceSectionBuilder? nativeResources = null, @@ -48,6 +48,19 @@ public ManagedPEBuilder( Func, BlobContentId>? deterministicIdProvider = null) : base(header, deterministicIdProvider) { + if (header is null) + { + Throw.ArgumentNull(nameof(header)); + } + if (metadataRootBuilder is null) + { + Throw.ArgumentNull(nameof(metadataRootBuilder)); + } + if (ilStream is null) + { + Throw.ArgumentNull(nameof(ilStream)); + } + if (strongNameSignatureSize < 0) { Throw.ArgumentOutOfRange(nameof(strongNameSignatureSize)); @@ -212,8 +225,17 @@ protected internal override PEDirectoriesBuilder GetDirectories() return _peDirectoriesBuilder; } - public void Sign(BlobBuilder peImage!!, Func, byte[]> signatureProvider!!) + public void Sign(BlobBuilder peImage, Func, byte[]> signatureProvider) { + if (peImage is null) + { + Throw.ArgumentNull(nameof(peImage)); + } + if (signatureProvider is null) + { + Throw.ArgumentNull(nameof(signatureProvider)); + } + Sign(peImage!, _lazyStrongNameSignature, signatureProvider!); } } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs index 7222ca86fc1d4a..51a90c19f4286a 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs @@ -23,8 +23,13 @@ protected readonly struct Section public readonly string Name; public readonly SectionCharacteristics Characteristics; - public Section(string name!!, SectionCharacteristics characteristics) + public Section(string name, SectionCharacteristics characteristics) { + if (name is null) + { + Throw.ArgumentNull(nameof(name)); + } + Name = name; Characteristics = characteristics; } @@ -53,8 +58,13 @@ public SerializedSection(BlobBuilder builder, string name, SectionCharacteristic public int VirtualSize => Builder.Count; } - protected PEBuilder(PEHeaderBuilder header!!, Func, BlobContentId>? deterministicIdProvider) + protected PEBuilder(PEHeaderBuilder header, Func, BlobContentId>? deterministicIdProvider) { + if (header is null) + { + Throw.ArgumentNull(nameof(header)); + } + IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider(); IsDeterministic = deterministicIdProvider != null; Header = header; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs index 795a45d6a87410..ac490b2ef19a81 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs @@ -70,8 +70,13 @@ public PEHeaders(Stream peStream, int size) /// The stream doesn't support seek operations. /// is null. /// Size is negative or extends past the end of the stream. - public PEHeaders(Stream peStream!!, int size, bool isLoadedImage) + public PEHeaders(Stream peStream, int size, bool isLoadedImage) { + if (peStream is null) + { + Throw.ArgumentNull(nameof(peStream)); + } + if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs index 4e5dedd718a167..be70102491819f 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs @@ -69,8 +69,13 @@ public unsafe PEReader(byte* peImage, int size) /// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the . /// The content of the image is not read during the construction of the /// - public unsafe PEReader(byte* peImage!!, int size, bool isLoadedImage) + public unsafe PEReader(byte* peImage, int size, bool isLoadedImage) { + if (peImage is null) + { + Throw.ArgumentNull(nameof(peImage)); + } + if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); @@ -145,8 +150,13 @@ public PEReader(Stream peStream, PEStreamOptions options) /// Size is negative or extends past the end of the stream. /// Error reading from the stream (only when prefetching data). /// is specified and the PE headers of the image are invalid. - public unsafe PEReader(Stream peStream!!, PEStreamOptions options, int size) + public unsafe PEReader(Stream peStream, PEStreamOptions options, int size) { + if (peStream is null) + { + Throw.ArgumentNull(nameof(peStream)); + } + if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); @@ -215,7 +225,7 @@ public PEReader(ImmutableArray peImage) { if (peImage.IsDefault) { - throw new ArgumentNullException(nameof(peImage)); + Throw.ArgumentNull(nameof(peImage)); } _peImage = new ByteArrayMemoryProvider(peImage); @@ -490,8 +500,13 @@ public PEMemoryBlock GetSectionData(int relativeVirtualAddress) /// /// is null. /// PE image not available. - public PEMemoryBlock GetSectionData(string sectionName!!) + public PEMemoryBlock GetSectionData(string sectionName) { + if (sectionName is null) + { + Throw.ArgumentNull(nameof(sectionName)); + } + int sectionIndex = PEHeaders.IndexOfSection(sectionName); if (sectionIndex < 0) { @@ -682,8 +697,17 @@ internal static PdbChecksumDebugDirectoryData DecodePdbChecksumDebugDirectoryDat /// The stream returned from doesn't support read and seek operations. /// No matching PDB file is found due to an error: The PE image or the PDB is invalid. /// No matching PDB file is found due to an error: An IO error occurred while reading the PE image or the PDB. - public bool TryOpenAssociatedPortablePdb(string peImagePath!!, Func pdbFileStreamProvider!!, out MetadataReaderProvider? pdbReaderProvider, out string? pdbPath) + public bool TryOpenAssociatedPortablePdb(string peImagePath, Func pdbFileStreamProvider, out MetadataReaderProvider? pdbReaderProvider, out string? pdbPath) { + if (peImagePath is null) + { + Throw.ArgumentNull(nameof(peImagePath)); + } + if (pdbFileStreamProvider is null) + { + Throw.ArgumentNull(nameof(pdbFileStreamProvider)); + } + pdbReaderProvider = null; pdbPath = null; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs index c76a7cb88fdd8c..a6bb5650c0c66b 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs @@ -269,8 +269,13 @@ public sealed override MethodBase BindToMethod( // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static MethodBase? ExactBinding(MethodBase[] match!!, Type[] types, ParameterModifier[]? modifiers) + public static MethodBase? ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { + if (match is null) + { + throw new ArgumentNullException(nameof(match)); + } + MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; @@ -309,8 +314,13 @@ public sealed override MethodBase BindToMethod( // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match!!, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) + public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { + if (match is null) + { + throw new ArgumentNullException(nameof(match)); + } + PropertyInfo? bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i = 0; i < match.Length; i++) diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs index 897ce6890a6545..eab0eb34511293 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.Apis.cs @@ -103,8 +103,11 @@ public sealed partial class MetadataLoadContext : IDisposable /// /// The name of the assembly that contains the core types such as System.Object. Typically, this would be "mscorlib". /// - public MetadataLoadContext(MetadataAssemblyResolver resolver!!, string? coreAssemblyName = null) + public MetadataLoadContext(MetadataAssemblyResolver resolver, string? coreAssemblyName = null) { + if (resolver is null) + throw new ArgumentNullException(nameof(resolver)); + this.resolver = resolver; if (coreAssemblyName != null) @@ -122,8 +125,11 @@ public MetadataLoadContext(MetadataAssemblyResolver resolver!!, string? coreAsse /// assembly with the same name was already loaded into the MetadataLoadContext, the prior assembly will be returned. If the /// two assemblies do not have the same Mvid, this method throws a FileLoadException. /// - public Assembly LoadFromAssemblyPath(string assemblyPath!!) + public Assembly LoadFromAssemblyPath(string assemblyPath) { + if (assemblyPath is null) + throw new ArgumentNullException(nameof(assemblyPath)); + if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); return LoadFromStreamCore(File.OpenRead(assemblyPath)); @@ -134,8 +140,11 @@ public Assembly LoadFromAssemblyPath(string assemblyPath!!) /// assembly with the same name was already loaded into the MetadataLoadContext, the prior assembly will be returned. If the /// two assemblies do not have the same Mvid, this method throws a FileLoadException. /// - public Assembly LoadFromByteArray(byte[] assembly!!) + public Assembly LoadFromByteArray(byte[] assembly) { + if (assembly is null) + throw new ArgumentNullException(nameof(assembly)); + if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); return LoadFromStreamCore(new MemoryStream(assembly)); @@ -149,8 +158,11 @@ public Assembly LoadFromByteArray(byte[] assembly!!) /// The MetadataLoadContext takes ownership of the Stream passed into this method. The original owner must not mutate its position, dispose the Stream or /// assume that its position will stay unchanged. /// - public Assembly LoadFromStream(Stream assembly!!) + public Assembly LoadFromStream(Stream assembly) { + if (assembly is null) + throw new ArgumentNullException(nameof(assembly)); + if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); assembly.Position = 0; @@ -164,8 +176,11 @@ public Assembly LoadFromStream(Stream assembly!!) /// Note that this behavior matches the behavior of AssemblyLoadContext.LoadFromAssemblyName() but does not match the behavior of /// Assembly.ReflectionOnlyLoad(). (the latter gives up without raising its resolve event.) /// - public Assembly LoadFromAssemblyName(string assemblyName!!) + public Assembly LoadFromAssemblyName(string assemblyName) { + if (assemblyName is null) + throw new ArgumentNullException(nameof(assemblyName)); + if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); AssemblyName assemblyNameObject = new AssemblyName(assemblyName); @@ -180,8 +195,11 @@ public Assembly LoadFromAssemblyName(string assemblyName!!) /// Note that this behavior matches the behavior of AssemblyLoadContext.LoadFromAssemblyName() resolve event but does not match the behavior of /// Assembly.ReflectionOnlyLoad(). (the latter gives up without raising its resolve event.) /// - public Assembly LoadFromAssemblyName(AssemblyName assemblyName!!) + public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { + if (assemblyName is null) + throw new ArgumentNullException(nameof(assemblyName)); + if (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); RoAssemblyName refName = assemblyName.ToRoAssemblyName(); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs index 65cbcba0372f63..6366823a695ae8 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs @@ -29,8 +29,11 @@ public class PathAssemblyResolver : MetadataAssemblyResolver /// /// Thrown when assemblyPaths is null. /// Thrown when a path is invalid. - public PathAssemblyResolver(IEnumerable assemblyPaths!!) + public PathAssemblyResolver(IEnumerable assemblyPaths) { + if (assemblyPaths is null) + throw new ArgumentNullException(nameof(assemblyPaths)); + foreach (string path in assemblyPaths) { if (string.IsNullOrEmpty(path)) diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs index c105c220588336..7d5c407a672eed 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.ManifestResources.cs @@ -12,10 +12,12 @@ namespace System.Reflection.TypeLoading.Ecma /// internal sealed partial class EcmaAssembly { - public sealed override ManifestResourceInfo? GetManifestResourceInfo(string resourceName!!) + public sealed override ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { + if (resourceName is null) + throw new ArgumentNullException(nameof(resourceName)); if (resourceName.Length == 0) - throw new ArgumentException(nameof(resourceName)); + throw new ArgumentException(null, nameof(resourceName)); InternalManifestResourceInfo internalManifestResourceInfo = GetEcmaManifestModule().GetInternalManifestResourceInfo(resourceName); @@ -57,10 +59,12 @@ public sealed override string[] GetManifestResourceNames() [UnconditionalSuppressMessage("SingleFile", "IL3002:RequiresAssemblyFiles on Module.GetFile", Justification = "ResourceLocation should never be ContainedInAnotherAssembly if embedded in a single-file")] - public sealed override Stream? GetManifestResourceStream(string name!!) + public sealed override Stream? GetManifestResourceStream(string name) { + if (name is null) + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) - throw new ArgumentException(nameof(name)); + throw new ArgumentException(null, nameof(name)); InternalManifestResourceInfo internalManifestResourceInfo = GetEcmaManifestModule().GetInternalManifestResourceInfo(name); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs index eac7148ec78435..cc8fd4d5637045 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.Modules.cs @@ -59,8 +59,11 @@ public sealed override Module[] GetLoadedModules(bool getResourceModules) public abstract override event ModuleResolveEventHandler? ModuleResolve; - internal RoModule? GetRoModule(string name!!) + internal RoModule? GetRoModule(string name) { + if (name is null) + throw new ArgumentNullException(nameof(name)); + if (!TryGetAssemblyFileInfo(name, includeManifestModule: true, out AssemblyFileInfo afi)) return null; @@ -94,9 +97,13 @@ internal RoModule[] ComputeRoModules(bool getResourceModules) } #pragma warning disable CS8995 // Nullable type is null-checked and will throw if null. - public sealed override Module LoadModule(string moduleName!!, byte[]? rawModule!!, byte[]? rawSymbolStore) + public sealed override Module LoadModule(string moduleName, byte[]? rawModule, byte[]? rawSymbolStore) #pragma warning restore CS8995 { + if (moduleName is null) + throw new ArgumentNullException(nameof(moduleName)); + if (rawModule is null) + throw new ArgumentNullException(nameof(rawModule)); if (!TryGetAssemblyFileInfo(moduleName, includeManifestModule: false, out AssemblyFileInfo afi)) throw new ArgumentException(SR.Format(SR.SpecifiedFileNameInvalid, moduleName)); // Name not in manifest. diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs index 28d2ebc00feb6e..d59d3271dacd08 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs @@ -96,8 +96,13 @@ public sealed override IEnumerable ExportedTypes } // Api to retrieve types by name. Retrieves both types physically defined in this module and types this assembly forwards from another assembly. - public sealed override Type? GetType(string name!!, bool throwOnError, bool ignoreCase) + public sealed override Type? GetType(string name, bool throwOnError, bool ignoreCase) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + // Known compat disagreement: This api is supposed to throw an ArgumentException if the name has an assembly qualification // (though the intended meaning seems clear.) This is difficult for us to implement as we don't have our own type name parser. // (We can't just throw in the assemblyResolve delegate because assembly qualifications are permitted inside generic arguments, diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs index 8a7f7ce7b7ae78..d10edff2d38b19 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/Helpers.cs @@ -239,8 +239,11 @@ public static string ToString(this IRoMethodBase roMethodBase, MethodSig return sb.ToString(); } - public static bool HasSameMetadataDefinitionAsCore(this M thisMember, MemberInfo other!!) where M : MemberInfo + public static bool HasSameMetadataDefinitionAsCore(this M thisMember, MemberInfo other) where M : MemberInfo { + if (other is null) + throw new ArgumentNullException(nameof(other)); + // Ensure that "other" is one of our MemberInfo objects. Do this check before calling any methods on it! if (!(other is M)) return false; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs index 0d0f122a35bd5b..39c0260d649406 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs @@ -100,8 +100,11 @@ public sealed override bool Equals([NotNullWhen(true)] object? obj) public sealed override MethodInfo GetGenericMethodDefinition() => IsGenericMethodDefinition ? this : throw new InvalidOperationException(); // Very uninformative but compatible exception [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 sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments!!) + public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) { + if (typeArguments is null) + throw new ArgumentNullException(nameof(typeArguments)); + if (!IsGenericMethodDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs index bd6cef84f36262..4442a1b9db2821 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs @@ -169,8 +169,13 @@ private QueryResult Query(BindingFlags bindingAttr) where M : MemberInfo return Query(null, bindingAttr, null); } - private QueryResult Query(string name!!, BindingFlags bindingAttr) where M : MemberInfo + private QueryResult Query(string name, BindingFlags bindingAttr) where M : MemberInfo { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + return Query(name, bindingAttr, null); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs index 52919a1315581a..0545cf4ce7826a 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.GetMember.cs @@ -9,13 +9,23 @@ namespace System.Reflection.TypeLoading internal abstract partial class RoType { public sealed override MemberInfo[] GetMembers(BindingFlags bindingAttr) => GetMemberImpl(null, MemberTypes.All, bindingAttr); - public sealed override MemberInfo[] GetMember(string name!!, BindingFlags bindingAttr) + public sealed override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + return GetMemberImpl(name, MemberTypes.All, bindingAttr); } - public sealed override MemberInfo[] GetMember(string name!!, MemberTypes type, BindingFlags bindingAttr) + public sealed override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + return GetMemberImpl(name, type, bindingAttr); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs index f7ddc728ba12fa..5b1f4ec062fa74 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoDefinitionType.cs @@ -85,8 +85,11 @@ public sealed override IEnumerable CustomAttributes internal abstract IEnumerable SpecializeInterfaces(RoType[] instantiation); [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 sealed override Type MakeGenericType(params Type[] typeArguments!!) + public sealed override Type MakeGenericType(params Type[] typeArguments) { + if (typeArguments is null) + throw new ArgumentNullException(nameof(typeArguments)); + if (!IsGenericTypeDefinition) throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs index 6f83b51797a64b..85c33b83f6fb33 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.GetInterface.cs @@ -8,8 +8,13 @@ namespace System.Reflection.TypeLoading /// internal abstract partial class RoType { - public sealed override Type? GetInterface(string name!!, bool ignoreCase) + public sealed override Type? GetInterface(string name, bool ignoreCase) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + name.SplitTypeName(out string ns, out string simpleName); Type? match = null; diff --git a/src/libraries/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.cs b/src/libraries/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.cs index 49e722736dd4a7..4a0c058a7f2d13 100644 --- a/src/libraries/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.cs +++ b/src/libraries/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.cs @@ -8,22 +8,28 @@ namespace System.Reflection public static class TypeExtensions { public static ConstructorInfo? GetConstructor( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] this Type type, Type[] types) { + ArgumentNullException.ThrowIfNull(type); + return type.GetConstructor(types); } public static ConstructorInfo[] GetConstructors( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] this Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetConstructors(); } public static ConstructorInfo[] GetConstructors( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetConstructors(bindingAttr); } @@ -34,75 +40,97 @@ public static MemberInfo[] GetDefaultMembers( | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors - | DynamicallyAccessedMemberTypes.PublicNestedTypes)] this Type type!!) + | DynamicallyAccessedMemberTypes.PublicNestedTypes)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetDefaultMembers(); } public static EventInfo? GetEvent( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetEvent(name); } public static EventInfo? GetEvent( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type, string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetEvent(name, bindingAttr); } public static EventInfo[] GetEvents( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetEvents(); } public static EventInfo[] GetEvents( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetEvents(bindingAttr); } public static FieldInfo? GetField( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetField(name); } public static FieldInfo? GetField( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type, string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetField(name, bindingAttr); } public static FieldInfo[] GetFields( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetFields(); } public static FieldInfo[] GetFields( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetFields(bindingAttr); } - public static Type[] GetGenericArguments(this Type type!!) + public static Type[] GetGenericArguments(this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetGenericArguments(); } public static Type[] GetInterfaces( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] this Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetInterfaces(); } @@ -113,17 +141,21 @@ public static MemberInfo[] GetMember( | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors - | DynamicallyAccessedMemberTypes.PublicNestedTypes)] this Type type!!, + | DynamicallyAccessedMemberTypes.PublicNestedTypes)] this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMember(name); } public static MemberInfo[] GetMember( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] this Type type, string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMember(name, bindingAttr); } @@ -134,121 +166,155 @@ public static MemberInfo[] GetMembers( | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors - | DynamicallyAccessedMemberTypes.PublicNestedTypes)] this Type type!!) + | DynamicallyAccessedMemberTypes.PublicNestedTypes)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMembers(); } public static MemberInfo[] GetMembers( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMembers(bindingAttr); } public static MethodInfo? GetMethod( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethod(name); } public static MethodInfo? GetMethod( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type, string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethod(name, bindingAttr); } public static MethodInfo? GetMethod( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type, string name, Type[] types) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethod(name, types); } public static MethodInfo[] GetMethods( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethods(); } public static MethodInfo[] GetMethods( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetMethods(bindingAttr); } public static Type? GetNestedType( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] this Type type, string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetNestedType(name, bindingAttr); } public static Type[] GetNestedTypes( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetNestedTypes(bindingAttr); } public static PropertyInfo[] GetProperties( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type!!) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperties(); } public static PropertyInfo[] GetProperties( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperties(bindingAttr); } public static PropertyInfo? GetProperty( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type, string name) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperty(name); } public static PropertyInfo? GetProperty( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type, string name, BindingFlags bindingAttr) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperty(name, bindingAttr); } public static PropertyInfo? GetProperty( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type, string name, Type? returnType) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperty(name, returnType); } public static PropertyInfo? GetProperty( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type, string name, Type? returnType, Type[] types) { + ArgumentNullException.ThrowIfNull(type); + return type.GetProperty(name, returnType, types); } - public static bool IsAssignableFrom(this Type type!!, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] Type? c) + public static bool IsAssignableFrom(this Type type, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] Type? c) { + ArgumentNullException.ThrowIfNull(type); + return type.IsAssignableFrom(c); } - public static bool IsInstanceOfType(this Type type!!, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? o) + public static bool IsInstanceOfType(this Type type, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? o) { + ArgumentNullException.ThrowIfNull(type); + return type.IsInstanceOfType(o); } } @@ -256,52 +322,70 @@ public static bool IsInstanceOfType(this Type type!!, [System.Diagnostics.CodeAn public static class AssemblyExtensions { [RequiresUnreferencedCode("Types might be removed")] - public static Type[] GetExportedTypes(this Assembly assembly!!) + public static Type[] GetExportedTypes(this Assembly assembly) { + ArgumentNullException.ThrowIfNull(assembly); + return assembly.GetExportedTypes(); } - public static Module[] GetModules(this Assembly assembly!!) + public static Module[] GetModules(this Assembly assembly) { + ArgumentNullException.ThrowIfNull(assembly); + return assembly.GetModules(); } [RequiresUnreferencedCode("Types might be removed")] - public static Type[] GetTypes(this Assembly assembly!!) + public static Type[] GetTypes(this Assembly assembly) { + ArgumentNullException.ThrowIfNull(assembly); + return assembly.GetTypes(); } } public static class EventInfoExtensions { - public static MethodInfo? GetAddMethod(this EventInfo eventInfo!!) + public static MethodInfo? GetAddMethod(this EventInfo eventInfo) { + ArgumentNullException.ThrowIfNull(eventInfo); + return eventInfo.GetAddMethod(); } - public static MethodInfo? GetAddMethod(this EventInfo eventInfo!!, bool nonPublic) + public static MethodInfo? GetAddMethod(this EventInfo eventInfo, bool nonPublic) { + ArgumentNullException.ThrowIfNull(eventInfo); + return eventInfo.GetAddMethod(nonPublic); } - public static MethodInfo? GetRaiseMethod(this EventInfo eventInfo!!) + public static MethodInfo? GetRaiseMethod(this EventInfo eventInfo) { + ArgumentNullException.ThrowIfNull(eventInfo); + return eventInfo.GetRaiseMethod(); } - public static MethodInfo? GetRaiseMethod(this EventInfo eventInfo!!, bool nonPublic) + public static MethodInfo? GetRaiseMethod(this EventInfo eventInfo, bool nonPublic) { + ArgumentNullException.ThrowIfNull(eventInfo); + return eventInfo.GetRaiseMethod(nonPublic); } - public static MethodInfo? GetRemoveMethod(this EventInfo eventInfo!!) + public static MethodInfo? GetRemoveMethod(this EventInfo eventInfo) { + ArgumentNullException.ThrowIfNull(eventInfo); + return eventInfo.GetRemoveMethod(); } - public static MethodInfo? GetRemoveMethod(this EventInfo eventInfo!!, bool nonPublic) + public static MethodInfo? GetRemoveMethod(this EventInfo eventInfo, bool nonPublic) { + ArgumentNullException.ThrowIfNull(eventInfo); + return eventInfo.GetRemoveMethod(nonPublic); } } @@ -314,8 +398,10 @@ public static class MemberInfoExtensions /// throws otherwise. /// /// This maybe - public static bool HasMetadataToken(this MemberInfo member!!) + public static bool HasMetadataToken(this MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + try { return GetMetadataTokenOrZeroOrThrow(member) != 0; @@ -334,8 +420,10 @@ public static bool HasMetadataToken(this MemberInfo member!!) /// /// There is no metadata token available. returns false in this case. /// - public static int GetMetadataToken(this MemberInfo member!!) + public static int GetMetadataToken(this MemberInfo member) { + ArgumentNullException.ThrowIfNull(member); + int token = GetMetadataTokenOrZeroOrThrow(member); if (token == 0) @@ -365,54 +453,72 @@ private static int GetMetadataTokenOrZeroOrThrow(this MemberInfo member) public static class MethodInfoExtensions { - public static MethodInfo GetBaseDefinition(this MethodInfo method!!) + public static MethodInfo GetBaseDefinition(this MethodInfo method) { + ArgumentNullException.ThrowIfNull(method); + return method.GetBaseDefinition(); } } public static class ModuleExtensions { - public static bool HasModuleVersionId(this Module module!!) + public static bool HasModuleVersionId(this Module module) { + ArgumentNullException.ThrowIfNull(module); + return true; // not expected to fail on platforms with Module.ModuleVersionId built-in. } - public static Guid GetModuleVersionId(this Module module!!) + public static Guid GetModuleVersionId(this Module module) { + ArgumentNullException.ThrowIfNull(module); + return module.ModuleVersionId; } } public static class PropertyInfoExtensions { - public static MethodInfo[] GetAccessors(this PropertyInfo property!!) + public static MethodInfo[] GetAccessors(this PropertyInfo property) { + ArgumentNullException.ThrowIfNull(property); + return property.GetAccessors(); } - public static MethodInfo[] GetAccessors(this PropertyInfo property!!, bool nonPublic) + public static MethodInfo[] GetAccessors(this PropertyInfo property, bool nonPublic) { + ArgumentNullException.ThrowIfNull(property); + return property.GetAccessors(nonPublic); } - public static MethodInfo? GetGetMethod(this PropertyInfo property!!) + public static MethodInfo? GetGetMethod(this PropertyInfo property) { + ArgumentNullException.ThrowIfNull(property); + return property.GetGetMethod(); } - public static MethodInfo? GetGetMethod(this PropertyInfo property!!, bool nonPublic) + public static MethodInfo? GetGetMethod(this PropertyInfo property, bool nonPublic) { + ArgumentNullException.ThrowIfNull(property); + return property.GetGetMethod(nonPublic); } - public static MethodInfo? GetSetMethod(this PropertyInfo property!!) + public static MethodInfo? GetSetMethod(this PropertyInfo property) { + ArgumentNullException.ThrowIfNull(property); + return property.GetSetMethod(); } - public static MethodInfo? GetSetMethod(this PropertyInfo property!!, bool nonPublic) + public static MethodInfo? GetSetMethod(this PropertyInfo property, bool nonPublic) { + ArgumentNullException.ThrowIfNull(property); + return property.GetSetMethod(nonPublic); } } diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs index 178ad1d94e0f97..c7d52eebb8296f 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/PreserializedResourceWriter.cs @@ -68,8 +68,21 @@ public partial class PreserializedResourceWriter /// Resource name /// Value of the resource in string form understood by the type's TypeConverter /// Assembly qualified type name of the resource - public void AddResource(string name!!, string value!!, string typeName!!) + public void AddResource(string name, string value, string typeName) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (typeName is null) + { + throw new ArgumentNullException(nameof(typeName)); + } + // determine if the type is a primitive type if (s_primitiveTypes.TryGetValue(typeName, out Type? primitiveType)) { @@ -112,8 +125,21 @@ public void AddResource(string name!!, string value!!, string typeName!!) /// Resource name /// Value of the resource in byte[] form understood by the type's TypeConverter /// Assembly qualified type name of the resource - public void AddTypeConverterResource(string name!!, byte[] value!!, string typeName!!) + public void AddTypeConverterResource(string name, byte[] value, string typeName) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (typeName is null) + { + throw new ArgumentNullException(nameof(typeName)); + } + AddResourceData(name, typeName, new ResourceDataRecord(SerializationFormat.TypeConverterByteArray, value)); _requiresDeserializingResourceReader = true; @@ -126,8 +152,17 @@ public void AddTypeConverterResource(string name!!, byte[] value!!, string typeN /// Resource name /// Value of the resource in byte[] form understood by BinaryFormatter /// Assembly qualified type name of the resource - public void AddBinaryFormattedResource(string name!!, byte[] value!!, string? typeName = null) + public void AddBinaryFormattedResource(string name, byte[] value, string? typeName = null) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (typeName == null) { // Some resx-files are missing type information for binary-formatted resources. @@ -153,8 +188,21 @@ public void AddBinaryFormattedResource(string name!!, byte[] value!!, string? ty /// Value of the resource in Stream form understood by the types constructor /// Assembly qualified type name of the resource /// Indicates that the stream should be closed after resources have been written - public void AddActivatorResource(string name!!, Stream value!!, string typeName!!, bool closeAfterWrite = false) + public void AddActivatorResource(string name, Stream value, string typeName, bool closeAfterWrite = false) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (typeName is null) + { + throw new ArgumentNullException(nameof(typeName)); + } + if (!value.CanSeek) throw new ArgumentException(SR.NotSupported_UnseekableStream); diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs index ce1758976ef665..cd7386c3773688 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/TypeNameComparer.cs @@ -52,9 +52,18 @@ private static bool IsMscorlib(ReadOnlySpan assemblyName) // If a type name is missing assembly, we assume it came from mscorlib // since this is what Type.GetType will do. #pragma warning disable CS8767 // This API member has [AllowNull] implemented interface, but we don't want to accept nulls here. - public bool Equals(string assemblyQualifiedTypeName1!!, string assemblyQualifiedTypeName2!!) + public bool Equals(string assemblyQualifiedTypeName1, string assemblyQualifiedTypeName2) #pragma warning restore CS8767 { + if (assemblyQualifiedTypeName1 is null) + { + throw new ArgumentNullException(nameof(assemblyQualifiedTypeName1)); + } + if (assemblyQualifiedTypeName2 is null) + { + throw new ArgumentNullException(nameof(assemblyQualifiedTypeName2)); + } + if (ReferenceEquals(assemblyQualifiedTypeName1, assemblyQualifiedTypeName2)) return true; diff --git a/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs b/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs index fe18e14e7e7e42..ed95e2b3fc2947 100644 --- a/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs +++ b/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs @@ -22,16 +22,22 @@ public partial class ResourceWriter // Adds a resource of type Stream to the list of resources to be // written to a file. They aren't written until Generate() is called. // Doesn't close the Stream when done. - public void AddResource(string name!!, Stream? value) + public void AddResource(string name, Stream? value) { + ArgumentNullException.ThrowIfNull(name); + if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); AddResourceInternal(name, value, false); } - public void AddResourceData(string name!!, string typeName!!, byte[] serializedData!!) + public void AddResourceData(string name, string typeName, byte[] serializedData) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(typeName); + ArgumentNullException.ThrowIfNull(serializedData); + AddResourceData(name, typeName, (object)serializedData); } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs index 734cdea637908d..8ae008b84ef9c7 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryRemovedArguments.cs @@ -24,8 +24,17 @@ public ObjectCache Source get { return _source; } } - public CacheEntryRemovedArguments(ObjectCache source!!, CacheEntryRemovedReason reason, CacheItem cacheItem!!) + public CacheEntryRemovedArguments(ObjectCache source, CacheEntryRemovedReason reason, CacheItem cacheItem) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + if (cacheItem is null) + { + throw new ArgumentNullException(nameof(cacheItem)); + } + _source = source; _reason = reason; _cacheItem = cacheItem; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs index d660879abdd5de..38b75f4e57ec21 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheEntryUpdateArguments.cs @@ -46,8 +46,17 @@ public CacheItemPolicy UpdatedCacheItemPolicy set { _updatedCacheItemPolicy = value; } } - public CacheEntryUpdateArguments(ObjectCache source!!, CacheEntryRemovedReason reason, string key!!, string regionName) + public CacheEntryUpdateArguments(ObjectCache source, CacheEntryRemovedReason reason, string key, string regionName) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + _source = source; _reason = reason; _key = key; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs index 596a33e77942bb..06b4e127139882 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/ChangeMonitor.cs @@ -219,8 +219,13 @@ public void Dispose() // on subsequent calls. The OnChangedCallback is guaranteed to be called exactly once. // It will be called when the dependency changes, or if it has already changed, it will // be called immediately (on the same thread??). - public void NotifyOnChanged(OnChangedCallback onChangedCallback!!) + public void NotifyOnChanged(OnChangedCallback onChangedCallback) { + if (onChangedCallback is null) + { + throw new ArgumentNullException(nameof(onChangedCallback)); + } + if (Interlocked.CompareExchange(ref _onChangedCallback, onChangedCallback, null) != null) { throw new InvalidOperationException(SR.Method_already_invoked); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs index 589dd3d97f9e8c..fb91beb33db7d9 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs @@ -21,7 +21,7 @@ internal sealed class Counters : EventSource private DiagnosticCounter[] _counters; private long[] _counterValues; - internal Counters(string cacheName!!) : base(EVENT_SOURCE_NAME_ROOT + cacheName) + internal Counters(string cacheName) : base(EVENT_SOURCE_NAME_ROOT + (cacheName ?? throw new ArgumentNullException(nameof(cacheName)))) { InitDisposableMembers(cacheName); } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs index a5ec31c515963d..22595a4bd5845a 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs @@ -93,8 +93,17 @@ internal FileChangeNotificationSystem() _lock = new object(); } - void IFileChangeNotificationSystem.StartMonitoring(string filePath!!, OnChangedCallback onChangedCallback!!, out object state, out DateTimeOffset lastWriteTime, out long fileSize) + void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize) { + if (filePath is null) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (onChangedCallback is null) + { + throw new ArgumentNullException(nameof(onChangedCallback)); + } + FileInfo fileInfo = new FileInfo(filePath); string dir = Path.GetDirectoryName(filePath); DirectoryMonitor dirMon = _dirMonitors[dir] as DirectoryMonitor; @@ -135,8 +144,17 @@ void IFileChangeNotificationSystem.StartMonitoring(string filePath!!, OnChangedC fileSize = (fileInfo.Exists) ? fileInfo.Length : -1; } - void IFileChangeNotificationSystem.StopMonitoring(string filePath!!, object state!!) + void IFileChangeNotificationSystem.StopMonitoring(string filePath, object state) { + if (filePath is null) + { + throw new ArgumentNullException(nameof(filePath)); + } + if (state is null) + { + throw new ArgumentNullException(nameof(state)); + } + FileChangeEventTarget target = state as FileChangeEventTarget; if (target == null) { diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs index 32ea27babe1fe5..e19fffd2cb1884 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/HostFileChangeMonitor.cs @@ -155,8 +155,13 @@ protected override void Dispose(bool disposing) public override string UniqueId { get { return _uniqueId; } } public override DateTimeOffset LastModified { get { return _lastModified; } } - public HostFileChangeMonitor(IList filePaths!!) + public HostFileChangeMonitor(IList filePaths) { + if (filePaths is null) + { + throw new ArgumentNullException(nameof(filePaths)); + } + if (filePaths.Count == 0) { throw new ArgumentException(RH.Format(SR.Empty_collection, nameof(filePaths))); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs index 408cacb1e6a1cf..527dc9ac7b7da3 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs @@ -348,8 +348,13 @@ private MemoryCache() Init(null); } - public MemoryCache(string name!!, NameValueCollection config = null) + public MemoryCache(string name, NameValueCollection config = null) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Empty_string_invalid, nameof(name)); @@ -364,8 +369,13 @@ public MemoryCache(string name!!, NameValueCollection config = null) // ignoreConfigSection is used when redirecting ASP.NET cache into the MemoryCache. This avoids infinite recursion // due to the fact that the (ASP.NET) config system uses the cache, and the cache uses the config system. - public MemoryCache(string name!!, NameValueCollection config, bool ignoreConfigSection) + public MemoryCache(string name, NameValueCollection config, bool ignoreConfigSection) { + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (name.Length == 0) { throw new ArgumentException(SR.Empty_string_invalid, nameof(name)); @@ -391,8 +401,13 @@ private void Init(NameValueCollection config) InitDisposableMembers(config); } - private object AddOrGetExistingInternal(string key!!, object value, CacheItemPolicy policy) + private object AddOrGetExistingInternal(string key, object value, CacheItemPolicy policy) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + DateTimeOffset absExp = ObjectCache.InfiniteAbsoluteExpiration; TimeSpan slidingExp = ObjectCache.NoSlidingExpiration; CacheItemPriority priority = CacheItemPriority.Default; @@ -620,8 +635,13 @@ public override object AddOrGetExisting(string key, object value, DateTimeOffset return AddOrGetExistingInternal(key, value, policy); } - public override CacheItem AddOrGetExisting(CacheItem item!!, CacheItemPolicy policy) + public override CacheItem AddOrGetExisting(CacheItem item, CacheItemPolicy policy) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + return new CacheItem(item.Key, AddOrGetExistingInternal(item.Key, item.Value, policy)); } @@ -656,8 +676,13 @@ public override void Set(string key, object value, DateTimeOffset absoluteExpira Set(key, value, policy); } - public override void Set(CacheItem item!!, CacheItemPolicy policy) + public override void Set(CacheItem item, CacheItemPolicy policy) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + Set(item.Key, item.Value, policy); } @@ -712,13 +737,18 @@ public override void Set(string key, object value, CacheItemPolicy policy, strin store.Set(cacheKey, new MemoryCacheEntry(key, value, absExp, slidingExp, priority, changeMonitors, removedCallback, this)); } - internal void Set(string key!!, + internal void Set(string key, object value, Collection changeMonitors, DateTimeOffset absoluteExpiration, TimeSpan slidingExpiration, CacheEntryUpdateCallback onUpdateCallback) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (changeMonitors == null && absoluteExpiration == ObjectCache.InfiniteAbsoluteExpiration && slidingExpiration == ObjectCache.NoSlidingExpiration) @@ -873,8 +903,13 @@ public override IDictionary GetValues(IEnumerable keys, // used when redirecting ASP.NET cache into the MemoryCache. This avoids infinite recursion // due to the fact that the (ASP.NET) config system uses the cache, and the cache uses the // config system. - internal void UpdateConfig(NameValueCollection config!!) + internal void UpdateConfig(NameValueCollection config) { + if (config is null) + { + throw new ArgumentNullException(nameof(config)); + } + if (!IsDisposed) { _stats.UpdateConfig(config); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs index eb027e99ec7fc8..c84a72f29dbc02 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs @@ -104,7 +104,7 @@ internal DateTime UtcLastUpdateUsage } internal MemoryCacheEntry(string key, - object value!!, + object value, DateTimeOffset absExp, TimeSpan slidingExp, CacheItemPriority priority, @@ -112,6 +112,11 @@ internal MemoryCacheEntry(string key, CacheEntryRemovedCallback removedCallback, MemoryCache cache) : base(key) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _utcCreated = DateTime.UtcNow; _value = value; diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs index 6b9fdcea40ca74..cccea3eb2d1a45 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs @@ -256,8 +256,8 @@ public BigInteger(decimal value) /// /// [CLSCompliant(false)] - public BigInteger(byte[] value!!) : - this(new ReadOnlySpan(value)) + public BigInteger(byte[] value) : + this(new ReadOnlySpan(value ?? throw new ArgumentNullException(nameof(value)))) { } diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs index eba71385210dd3..c4fa725c6495e4 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs @@ -360,8 +360,10 @@ internal static bool TryParseBigInteger(ReadOnlySpan value, NumberStyles s } } - internal static BigInteger ParseBigInteger(string value!!, NumberStyles style, NumberFormatInfo info) + internal static BigInteger ParseBigInteger(string value, NumberStyles style, NumberFormatInfo info) { + ArgumentNullException.ThrowIfNull(value); + return ParseBigInteger(value.AsSpan(), style, info); } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs index 2b8963c0ad07fc..34f84d14034bcf 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterConverter.cs @@ -7,92 +7,126 @@ namespace System.Runtime.Serialization { public class FormatterConverter : IFormatterConverter { - public object Convert(object value!!, Type type) + public object Convert(object value, Type type) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } - public object Convert(object value!!, TypeCode typeCode) + public object Convert(object value, TypeCode typeCode) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); } - public bool ToBoolean(object value!!) + public bool ToBoolean(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture); } - public char ToChar(object value!!) + public char ToChar(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToChar(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] - public sbyte ToSByte(object value!!) + public sbyte ToSByte(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToSByte(value, CultureInfo.InvariantCulture); } - public byte ToByte(object value!!) + public byte ToByte(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToByte(value, CultureInfo.InvariantCulture); } - public short ToInt16(object value!!) + public short ToInt16(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToInt16(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] - public ushort ToUInt16(object value!!) + public ushort ToUInt16(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture); } - public int ToInt32(object value!!) + public int ToInt32(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToInt32(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] - public uint ToUInt32(object value!!) + public uint ToUInt32(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture); } - public long ToInt64(object value!!) + public long ToInt64(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToInt64(value, CultureInfo.InvariantCulture); } [CLSCompliant(false)] - public ulong ToUInt64(object value!!) + public ulong ToUInt64(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture); } - public float ToSingle(object value!!) + public float ToSingle(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToSingle(value, CultureInfo.InvariantCulture); } - public double ToDouble(object value!!) + public double ToDouble(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToDouble(value, CultureInfo.InvariantCulture); } - public decimal ToDecimal(object value!!) + public decimal ToDecimal(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture); } - public DateTime ToDateTime(object value!!) + public DateTime ToDateTime(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture); } - public string? ToString(object value!!) + public string? ToString(object value) { + ArgumentNullException.ThrowIfNull(value); + return System.Convert.ToString(value, CultureInfo.InvariantCulture); } } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs index 73e109f17b1378..b1692273bf11cf 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/FormatterServices.cs @@ -169,9 +169,11 @@ public static MemberInfo[] GetSerializableMembers( } public static MemberInfo[] GetSerializableMembers( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type!!, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, StreamingContext context) { + ArgumentNullException.ThrowIfNull(type); + // If we've already gathered the members for this type, just return them. // Otherwise, get them and add them. return s_memberInfoTable.GetOrAdd( @@ -210,8 +212,12 @@ internal static void SerializationSetValue(MemberInfo fi, object? target, object throw new ArgumentException(SR.Argument_InvalidFieldInfo); } - public static object PopulateObjectMembers(object obj!!, MemberInfo[] members!!, object?[] data!!) + public static object PopulateObjectMembers(object obj, MemberInfo[] members, object?[] data) { + ArgumentNullException.ThrowIfNull(obj); + ArgumentNullException.ThrowIfNull(members); + ArgumentNullException.ThrowIfNull(data); + if (members.Length != data.Length) { throw new ArgumentException(SR.Argument_DataLengthDifferent); @@ -248,8 +254,11 @@ public static object PopulateObjectMembers(object obj!!, MemberInfo[] members!!, return obj; } - public static object?[] GetObjectData(object obj!!, MemberInfo[] members!!) + public static object?[] GetObjectData(object obj, MemberInfo[] members) { + ArgumentNullException.ThrowIfNull(obj); + ArgumentNullException.ThrowIfNull(members); + object?[] data = new object[members.Length]; for (int i = 0; i < members.Length; i++) { @@ -270,14 +279,18 @@ public static object PopulateObjectMembers(object obj!!, MemberInfo[] members!!, return data; } - public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate!!) + public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { + ArgumentNullException.ThrowIfNull(innerSurrogate); + return new SurrogateForCyclicalReference(innerSurrogate); } [RequiresUnreferencedCode("Types might be removed")] - public static Type? GetTypeFromAssembly(Assembly assem!!, string name) + public static Type? GetTypeFromAssembly(Assembly assem, string name) { + ArgumentNullException.ThrowIfNull(assem); + return assem.GetType(name, throwOnError: false, ignoreCase: false); } @@ -296,8 +309,10 @@ internal static Assembly LoadAssemblyFromString(string assemblyName) return null; } - internal static string GetClrAssemblyName(Type type!!, out bool hasTypeForwardedFrom) + internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) { + ArgumentNullException.ThrowIfNull(type); + // Special case types like arrays Type attributedType = type; while (attributedType.HasElementType) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs index c5986bc8edb399..c9dfbcd3a79fdc 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs @@ -63,8 +63,10 @@ internal object? TopObject } } - internal ObjectReader(Stream stream!!, ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder) + internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder) { + ArgumentNullException.ThrowIfNull(stream); + _stream = stream; _surrogates = selector; _context = context; @@ -73,8 +75,10 @@ internal ObjectReader(Stream stream!!, ISurrogateSelector? selector, StreamingCo } [RequiresUnreferencedCode("Types might be removed")] - internal object Deserialize(BinaryParser serParser!!) + internal object Deserialize(BinaryParser serParser) { + ArgumentNullException.ThrowIfNull(serParser); + _fullDeserialization = false; TopObject = null; _topId = 0; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs index b7c3e57ac6d6df..bdf952a4ad6fd5 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs @@ -50,8 +50,11 @@ internal ObjectWriter(ISurrogateSelector? selector, StreamingContext context, In } [RequiresUnreferencedCode(ObjectWriterUnreferencedCodeMessage)] - internal void Serialize(object graph!!, BinaryFormatterWriter serWriter!!) + internal void Serialize(object graph, BinaryFormatterWriter serWriter) { + ArgumentNullException.ThrowIfNull(graph); + ArgumentNullException.ThrowIfNull(serWriter); + _serWriter = serWriter; serWriter.WriteBegin(); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs index c19f422bf33e14..646404a24ab26d 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectIDGenerator.cs @@ -61,8 +61,10 @@ private int FindElement(object obj, out bool found) // find the element, we generate an object id for it and insert the pair into the // table. We return an Int64 for the object id. The out parameter firstTime // is set to true if this is the first time that we have seen this object. - public virtual long GetId(object obj!!, out bool firstTime) + public virtual long GetId(object obj, out bool firstTime) { + ArgumentNullException.ThrowIfNull(obj); + bool found; int pos = FindElement(obj, out found); @@ -91,8 +93,10 @@ public virtual long GetId(object obj!!, out bool firstTime) // Checks to see if obj has already been assigned an id. If it has, // we return that id, otherwise we return 0. - public virtual long HasId(object obj!!, out bool firstTime) + public virtual long HasId(object obj, out bool firstTime) { + ArgumentNullException.ThrowIfNull(obj); + bool found; int pos = FindElement(obj, out found); if (found) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs index 6a3ef39fb0deb8..03392d66a5e777 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs @@ -658,8 +658,10 @@ internal void RegisterString(string? obj, long objectID, SerializationInfo? info } [RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)] - public void RegisterObject(object obj!!, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member, int[]? arrayIndex) + public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member, int[]? arrayIndex) { + ArgumentNullException.ThrowIfNull(obj); + if (objectID <= 0) { throw new ArgumentOutOfRangeException(nameof(objectID), SR.ArgumentOutOfRange_ObjectID); @@ -767,8 +769,10 @@ public void RegisterObject(object obj!!, long objectID, SerializationInfo? info, /// The SerializationInfo containing all info for obj. /// The streaming context in which the serialization is taking place. [RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)] - internal void CompleteISerializableObject(object obj!!, SerializationInfo? info, StreamingContext context) + internal void CompleteISerializableObject(object obj, SerializationInfo? info, StreamingContext context) { + ArgumentNullException.ThrowIfNull(obj); + if (!(obj is ISerializable)) { throw new ArgumentException(SR.Serialization_NotISer); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs index 17703be74d3b29..e8f87df23e6c96 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SurrogateSelector.cs @@ -11,8 +11,11 @@ public class SurrogateSelector : ISurrogateSelector internal readonly SurrogateHashtable _surrogates = new SurrogateHashtable(32); internal ISurrogateSelector? _nextSelector; - public virtual void AddSurrogate(Type type!!, StreamingContext context, ISerializationSurrogate surrogate!!) + public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(surrogate); + var key = new SurrogateKey(type, context); _surrogates.Add(key, surrogate); // Hashtable does duplicate checking. } @@ -47,8 +50,10 @@ private static bool HasCycle(ISurrogateSelector selector) // Adds another selector to check if we don't have match within this selector. // The logic is:"Add this onto the list as the first thing that you check after yourself." - public virtual void ChainSelector(ISurrogateSelector selector!!) + public virtual void ChainSelector(ISurrogateSelector selector) { + ArgumentNullException.ThrowIfNull(selector); + // Verify that we don't try and add ourself twice. if (selector == this) { @@ -136,8 +141,10 @@ public virtual void ChainSelector(ISurrogateSelector selector!!) // Gets the surrogate for a particular type. If this selector can't // provide a surrogate, it checks with all of it's children before returning null. - public virtual ISerializationSurrogate? GetSurrogate(Type type!!, StreamingContext context, out ISurrogateSelector selector) + public virtual ISerializationSurrogate? GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) { + ArgumentNullException.ThrowIfNull(type); + selector = this; SurrogateKey key = new SurrogateKey(type, context); @@ -155,8 +162,10 @@ public virtual void ChainSelector(ISurrogateSelector selector!!) // Removes the surrogate associated with a given type. Does not // check chained surrogates. - public virtual void RemoveSurrogate(Type type!!, StreamingContext context) + public virtual void RemoveSurrogate(Type type, StreamingContext context) { + ArgumentNullException.ThrowIfNull(type); + SurrogateKey key = new SurrogateKey(type, context); _surrogates.Remove(key); } diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs index 900191323067e0..ffb233d00f6d9e 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs @@ -108,8 +108,10 @@ public abstract class GenericAce // Marshal the ACE header into the given array starting at the given offset // - internal void MarshalHeader(byte[] binaryForm!!, int offset) + internal void MarshalHeader(byte[] binaryForm, int offset) { + ArgumentNullException.ThrowIfNull(binaryForm); + int Length = BinaryLength; // Invokes the most derived property if (offset < 0) @@ -237,8 +239,10 @@ internal static AceFlags AceFlagsFromInheritanceFlags(InheritanceFlags inheritan // Sanity-check the ACE header (used by the unmarshaling logic) // - internal static void VerifyHeader(byte[] binaryForm!!, int offset) + internal static void VerifyHeader(byte[] binaryForm, int offset) { + ArgumentNullException.ThrowIfNull(binaryForm); + if (offset < 0) { throw new ArgumentOutOfRangeException( @@ -652,9 +656,11 @@ public abstract class KnownAce : GenericAce #region Constructors - internal KnownAce(AceType type, AceFlags flags, int accessMask, SecurityIdentifier securityIdentifier!!) + internal KnownAce(AceType type, AceFlags flags, int accessMask, SecurityIdentifier securityIdentifier) : base(type, flags) { + ArgumentNullException.ThrowIfNull(securityIdentifier); + // // The values are set by invoking the properties. // diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs index 6651ab55b95257..58d42d4f6cc3cd 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs @@ -37,8 +37,10 @@ public sealed class AceEnumerator : IEnumerator #region Constructors - internal AceEnumerator(GenericAcl collection!!) + internal AceEnumerator(GenericAcl collection) { + ArgumentNullException.ThrowIfNull(collection); + _acl = collection; Reset(); } @@ -162,8 +164,10 @@ protected GenericAcl() #region ICollection Implementation - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) { throw new RankException(SR.Rank_MultiDimNotSupported); @@ -230,8 +234,10 @@ public sealed class RawAcl : GenericAcl #region Private Methods - private static void VerifyHeader(byte[] binaryForm!!, int offset, out byte revision, out int count, out int length) + private static void VerifyHeader(byte[] binaryForm, int offset, out byte revision, out int count, out int length) { + ArgumentNullException.ThrowIfNull(binaryForm); + if (offset < 0) { // @@ -271,8 +277,10 @@ private static void VerifyHeader(byte[] binaryForm!!, int offset, out byte revis throw new ArgumentOutOfRangeException(nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } - private void MarshalHeader(byte[] binaryForm!!, int offset) + private void MarshalHeader(byte[] binaryForm, int offset) { + ArgumentNullException.ThrowIfNull(binaryForm); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -547,8 +555,10 @@ public override GenericAce this[int index] // Adds an ACE at the specified index // - public void InsertAce(int index, GenericAce ace!!) + public void InsertAce(int index, GenericAce ace) { + ArgumentNullException.ThrowIfNull(ace); + if (BinaryLength + ace.BinaryLength > MaxBinaryLength) { throw new OverflowException(SR.AccessControl_AclTooLong); @@ -1833,9 +1843,11 @@ internal CommonAcl(bool isContainer, bool isDS, byte revision, int capacity) // copy of the ACL passed in // - internal CommonAcl(bool isContainer, bool isDS, RawAcl rawAcl!!, bool trusted, bool isDacl) + internal CommonAcl(bool isContainer, bool isDS, RawAcl rawAcl, bool trusted, bool isDacl) : base() { + ArgumentNullException.ThrowIfNull(rawAcl); + _isContainer = isContainer; _isDS = isDS; @@ -1956,8 +1968,10 @@ internal void CheckFlags(InheritanceFlags inheritanceFlags, PropagationFlags pro // Helper function behind all the AddXXX methods for qualified aces // - internal void AddQualifiedAce(SecurityIdentifier sid!!, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) + internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { + ArgumentNullException.ThrowIfNull(sid); + ThrowIfNotCanonical(); bool aceMerged = false; // if still false after all attempts to merge, create new entry @@ -2034,8 +2048,10 @@ internal void AddQualifiedAce(SecurityIdentifier sid!!, AceQualifier qualifier, // Helper function behind all the SetXXX methods // - internal void SetQualifiedAce(SecurityIdentifier sid!!, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) + internal void SetQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, int accessMask, AceFlags flags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType) { + ArgumentNullException.ThrowIfNull(sid); + if (qualifier == AceQualifier.SystemAudit && ((flags & AceFlags.AuditFlags) == 0)) { @@ -2817,8 +2833,10 @@ public void RemoveInheritedAces() OnAclModificationTried(); } - public void Purge(SecurityIdentifier sid!!) + public void Purge(SecurityIdentifier sid) { + ArgumentNullException.ThrowIfNull(sid); + ThrowIfNotCanonical(); for (int i = Count - 1; i >= 0; i--) diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs index 84ca62537f5404..bb64eaec0d2b69 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs @@ -222,8 +222,10 @@ private static bool AceNeedsTranslation([NotNullWhen(true)] CommonAce? ace, bool // // Modifies the DACL // - protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule!!, out bool modified) + protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try { @@ -347,8 +349,10 @@ protected override bool ModifyAccess(AccessControlModification modification, Acc // Modifies the SACL // - protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule!!, out bool modified) + protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try { @@ -425,8 +429,10 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi #region Public Methods - protected void AddAccessRule(AccessRule rule!!) + protected void AddAccessRule(AccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -439,8 +445,10 @@ protected void AddAccessRule(AccessRule rule!!) } } - protected void SetAccessRule(AccessRule rule!!) + protected void SetAccessRule(AccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -453,8 +461,10 @@ protected void SetAccessRule(AccessRule rule!!) } } - protected void ResetAccessRule(AccessRule rule!!) + protected void ResetAccessRule(AccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -469,8 +479,10 @@ protected void ResetAccessRule(AccessRule rule!!) return; } - protected bool RemoveAccessRule(AccessRule rule!!) + protected bool RemoveAccessRule(AccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -488,8 +500,10 @@ protected bool RemoveAccessRule(AccessRule rule!!) } } - protected void RemoveAccessRuleAll(AccessRule rule!!) + protected void RemoveAccessRuleAll(AccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -509,8 +523,10 @@ protected void RemoveAccessRuleAll(AccessRule rule!!) return; } - protected void RemoveAccessRuleSpecific(AccessRule rule!!) + protected void RemoveAccessRuleSpecific(AccessRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -528,8 +544,10 @@ protected void RemoveAccessRuleSpecific(AccessRule rule!!) } } - protected void AddAuditRule(AuditRule rule!!) + protected void AddAuditRule(AuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -542,8 +560,10 @@ protected void AddAuditRule(AuditRule rule!!) } } - protected void SetAuditRule(AuditRule rule!!) + protected void SetAuditRule(AuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -556,8 +576,10 @@ protected void SetAuditRule(AuditRule rule!!) } } - protected bool RemoveAuditRule(AuditRule rule!!) + protected bool RemoveAuditRule(AuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -570,8 +592,10 @@ protected bool RemoveAuditRule(AuditRule rule!!) } } - protected void RemoveAuditRuleAll(AuditRule rule!!) + protected void RemoveAuditRuleAll(AuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try @@ -584,8 +608,10 @@ protected void RemoveAuditRuleAll(AuditRule rule!!) } } - protected void RemoveAuditRuleSpecific(AuditRule rule!!) + protected void RemoveAuditRuleSpecific(AuditRule rule) { + ArgumentNullException.ThrowIfNull(rule); + WriteLock(); try diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs index d375fde326d44d..9bf2f9d7d490bc 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/NativeObjectSecurity.cs @@ -343,8 +343,10 @@ protected sealed override void Persist(string name, AccessControlSections includ Persist(name, includeSections, _exceptionContext); } - protected void Persist(string name!!, AccessControlSections includeSections, object? exceptionContext) + protected void Persist(string name, AccessControlSections includeSections, object? exceptionContext) { + ArgumentNullException.ThrowIfNull(name); + Persist(name, null, includeSections, exceptionContext); } @@ -359,8 +361,10 @@ protected sealed override void Persist(SafeHandle handle, AccessControlSections Persist(handle, includeSections, _exceptionContext); } - protected void Persist(SafeHandle handle!!, AccessControlSections includeSections, object? exceptionContext) + protected void Persist(SafeHandle handle, AccessControlSections includeSections, object? exceptionContext) { + ArgumentNullException.ThrowIfNull(handle); + Persist(null, handle, includeSections, exceptionContext); } #endregion diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs index 2edf3e0cc7dd85..a0103260f383c8 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ObjectSecurity.cs @@ -71,9 +71,11 @@ protected ObjectSecurity(bool isContainer, bool isDS) _securityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, ControlFlags.None, null, null, null, dacl); } - protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor!!) + protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor) : this() { + ArgumentNullException.ThrowIfNull(securityDescriptor); + _securityDescriptor = securityDescriptor; } @@ -356,8 +358,10 @@ protected virtual void Persist(SafeHandle handle, AccessControlSections includeS } } - public void SetOwner(IdentityReference identity!!) + public void SetOwner(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); + WriteLock(); try @@ -394,8 +398,10 @@ public void SetOwner(IdentityReference identity!!) } } - public void SetGroup(IdentityReference identity!!) + public void SetGroup(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); + WriteLock(); try @@ -409,8 +415,10 @@ public void SetGroup(IdentityReference identity!!) } } - public virtual void PurgeAccessRules(IdentityReference identity!!) + public virtual void PurgeAccessRules(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); + WriteLock(); try @@ -424,8 +432,9 @@ public virtual void PurgeAccessRules(IdentityReference identity!!) } } - public virtual void PurgeAuditRules(IdentityReference identity!!) + public virtual void PurgeAuditRules(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); WriteLock(); @@ -562,8 +571,10 @@ public void SetSecurityDescriptorSddlForm(string sddlForm) SetSecurityDescriptorSddlForm(sddlForm, AccessControlSections.All); } - public void SetSecurityDescriptorSddlForm(string sddlForm!!, AccessControlSections includeSections) + public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections) { + ArgumentNullException.ThrowIfNull(sddlForm); + if ((includeSections & AccessControlSections.All) == 0) { throw new ArgumentException( @@ -606,8 +617,10 @@ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm) SetSecurityDescriptorBinaryForm(binaryForm, AccessControlSections.All); } - public void SetSecurityDescriptorBinaryForm(byte[] binaryForm!!, AccessControlSections includeSections) + public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections) { + ArgumentNullException.ThrowIfNull(binaryForm); + if ((includeSections & AccessControlSections.All) == 0) { throw new ArgumentException( @@ -634,8 +647,10 @@ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm!!, AccessControlSe protected abstract bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified); protected abstract bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified); - public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule!!, out bool modified) + public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified) { + ArgumentNullException.ThrowIfNull(rule); + if (!this.AccessRuleType.IsAssignableFrom(rule.GetType())) { throw new ArgumentException( @@ -655,8 +670,10 @@ public virtual bool ModifyAccessRule(AccessControlModification modification, Acc } } - public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule!!, out bool modified) + public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified) { + ArgumentNullException.ThrowIfNull(rule); + if (!this.AuditRuleType.IsAssignableFrom(rule.GetType())) { throw new ArgumentException( diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs index c184a1ac9e15bc..9982df60152ac6 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Privilege.cs @@ -361,8 +361,10 @@ public bool IsImpersonating #region Constructors - public Privilege(string privilegeName!!) + public Privilege(string privilegeName) { + ArgumentNullException.ThrowIfNull(privilegeName); + this.luid = LuidFromPrivilege(privilegeName); } #endregion diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs index 3121312f613f15..ebce380b5cb68b 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/Rules.cs @@ -31,12 +31,14 @@ public abstract class AuthorizationRule #region Constructors protected internal AuthorizationRule( - IdentityReference identity!!, + IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { + ArgumentNullException.ThrowIfNull(identity); + if (accessMask == 0) { throw new ArgumentException(SR.Argument_ArgumentZero, nameof(accessMask)); diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs index 8ce2a85e103ad7..6b5c64c82c4443 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs @@ -257,8 +257,10 @@ public string GetSddlForm(AccessControlSections includeSections) // Converts the security descriptor to its binary form // - public void GetBinaryForm(byte[] binaryForm!!, int offset) + public void GetBinaryForm(byte[] binaryForm, int offset) { + ArgumentNullException.ThrowIfNull(binaryForm); + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), @@ -461,9 +463,11 @@ public RawSecurityDescriptor(string sddlForm) // Important: the representation must be in self-relative format // - public RawSecurityDescriptor(byte[] binaryForm!!, int offset) + public RawSecurityDescriptor(byte[] binaryForm, int offset) : base() { + ArgumentNullException.ThrowIfNull(binaryForm); + // // The array passed in must be valid // @@ -611,8 +615,10 @@ public RawSecurityDescriptor(byte[] binaryForm!!, int offset) #region Static Methods - private static byte[] BinaryFormFromSddlForm(string sddlForm!!) + private static byte[] BinaryFormFromSddlForm(string sddlForm) { + ArgumentNullException.ThrowIfNull(sddlForm); + int error; IntPtr byteArray = IntPtr.Zero; uint byteArraySize = 0; @@ -924,8 +930,10 @@ public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescript { } - internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor!!, bool trusted) + internal CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor, bool trusted) { + ArgumentNullException.ThrowIfNull(rawSecurityDescriptor); + CreateFromParts( isContainer, isDS, @@ -1179,16 +1187,20 @@ public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInherit } } - public void PurgeAccessControl(SecurityIdentifier sid!!) + public void PurgeAccessControl(SecurityIdentifier sid) { + ArgumentNullException.ThrowIfNull(sid); + if (DiscretionaryAcl != null) { DiscretionaryAcl.Purge(sid); } } - public void PurgeAudit(SecurityIdentifier sid!!) + public void PurgeAudit(SecurityIdentifier sid) { + ArgumentNullException.ThrowIfNull(sid); + if (SystemAcl != null) { SystemAcl.Purge(sid); diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs index 8e7e191416d0f7..e192e60119f064 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/Claim.cs @@ -56,8 +56,10 @@ public Claim(BinaryReader reader) /// a pointing to a . /// the value for , which is the that has these claims. /// if 'reader' is null. - public Claim(BinaryReader reader!!, ClaimsIdentity? subject) + public Claim(BinaryReader reader, ClaimsIdentity? subject) { + ArgumentNullException.ThrowIfNull(reader); + _subject = subject; SerializationMask mask = (SerializationMask)reader.ReadInt32(); @@ -246,8 +248,11 @@ public Claim(string type, string value, string? valueType, string? issuer, strin /// The subject that this claim describes. /// This allows adding a property when adding a Claim. /// The value associated with the property. - internal Claim(string type!!, string value!!, string? valueType, string? issuer, string? originalIssuer, ClaimsIdentity? subject, string? propertyKey, string? propertyValue) + internal Claim(string type, string value, string? valueType, string? issuer, string? originalIssuer, ClaimsIdentity? subject, string? propertyKey, string? propertyValue) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(value); + _type = type; _value = value; _valueType = string.IsNullOrEmpty(valueType) ? ClaimValueTypes.String : valueType; @@ -280,8 +285,10 @@ protected Claim(Claim other) /// the to assign to . /// will be set to 'subject'. /// if 'other' is null. - protected Claim(Claim other!!, ClaimsIdentity? subject) + protected Claim(Claim other, ClaimsIdentity? subject) { + ArgumentNullException.ThrowIfNull(other); + _issuer = other._issuer; _originalIssuer = other._originalIssuer; _subject = subject; @@ -414,8 +421,10 @@ public virtual void WriteTo(BinaryWriter writer) /// the to use for data storage. /// additional data provided by derived type. /// if 'writer' is null. - protected virtual void WriteTo(BinaryWriter writer!!, byte[]? userData) + protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) { + ArgumentNullException.ThrowIfNull(writer); + int numberOfPropertiesWritten = 1; SerializationMask mask = SerializationMask.None; if (string.Equals(_type, ClaimsIdentity.DefaultNameClaimType)) diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs index fa49abae75cb4f..a0f3e6bc1b15df 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs @@ -195,8 +195,10 @@ public ClaimsIdentity(IIdentity? identity, IEnumerable? claims, string? a /// /// a pointing to a . /// if 'reader' is null. - public ClaimsIdentity(BinaryReader reader!!) + public ClaimsIdentity(BinaryReader reader) { + ArgumentNullException.ThrowIfNull(reader); + Initialize(reader); } @@ -205,8 +207,10 @@ public ClaimsIdentity(BinaryReader reader!!) /// /// to copy. /// if 'other' is null. - protected ClaimsIdentity(ClaimsIdentity other!!) + protected ClaimsIdentity(ClaimsIdentity other) { + ArgumentNullException.ThrowIfNull(other); + if (other._actor != null) { _actor = other._actor.Clone(); @@ -409,8 +413,10 @@ public virtual ClaimsIdentity Clone() /// the add. /// If != this, then Claim.Clone(this) is called before the claim is added. /// if 'claim' is null. - public virtual void AddClaim(Claim claim!!) + public virtual void AddClaim(Claim claim) { + ArgumentNullException.ThrowIfNull(claim); + if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); @@ -427,8 +433,10 @@ public virtual void AddClaim(Claim claim!!) /// Enumeration of claims to add. /// Each claim is examined and if != this, then Claim.Clone(this) is called before the claim is added. /// if 'claims' is null. - public virtual void AddClaims(IEnumerable claims!!) + public virtual void AddClaims(IEnumerable claims) { + ArgumentNullException.ThrowIfNull(claims); + foreach (Claim? claim in claims) { if (claim == null) @@ -539,13 +547,19 @@ private void SafeAddClaim(Claim? claim) /// The function that performs the matching logic. /// A of matched claims. /// if 'match' is null. - public virtual IEnumerable FindAll(Predicate match!!) + public virtual IEnumerable FindAll(Predicate match) { - foreach (Claim claim in Claims) + ArgumentNullException.ThrowIfNull(match); + return Core(match); + + IEnumerable Core(Predicate match) { - if (match(claim)) + foreach (Claim claim in Claims) { - yield return claim; + if (match(claim)) + { + yield return claim; + } } } } @@ -557,15 +571,21 @@ public virtual IEnumerable FindAll(Predicate match!!) /// A of matched claims. /// Comparison is: StringComparison.OrdinalIgnoreCase. /// if 'type' is null. - public virtual IEnumerable FindAll(string type!!) + public virtual IEnumerable FindAll(string type) { - foreach (Claim claim in Claims) + ArgumentNullException.ThrowIfNull(type); + return Core(type); + + IEnumerable Core(string type) { - if (claim != null) + foreach (Claim claim in Claims) { - if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) + if (claim != null) { - yield return claim; + if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) + { + yield return claim; + } } } } @@ -577,8 +597,10 @@ public virtual IEnumerable FindAll(string type!!) /// The function that performs the matching logic. /// A , null if nothing matches. /// if 'match' is null. - public virtual Claim? FindFirst(Predicate match!!) + public virtual Claim? FindFirst(Predicate match) { + ArgumentNullException.ThrowIfNull(match); + foreach (Claim claim in Claims) { if (match(claim)) @@ -597,8 +619,10 @@ public virtual IEnumerable FindAll(string type!!) /// A , null if nothing matches. /// Comparison is: StringComparison.OrdinalIgnoreCase. /// if 'type' is null. - public virtual Claim? FindFirst(string type!!) + public virtual Claim? FindFirst(string type) { + ArgumentNullException.ThrowIfNull(type); + foreach (Claim claim in Claims) { if (claim != null) @@ -619,8 +643,10 @@ public virtual IEnumerable FindAll(string type!!) /// The function that performs the matching logic. /// true if a claim is found, false otherwise. /// if 'match' is null. - public virtual bool HasClaim(Predicate match!!) + public virtual bool HasClaim(Predicate match) { + ArgumentNullException.ThrowIfNull(match); + foreach (Claim claim in Claims) { if (match(claim)) @@ -641,8 +667,11 @@ public virtual bool HasClaim(Predicate match!!) /// Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value. /// if 'type' is null. /// if 'value' is null. - public virtual bool HasClaim(string type!!, string value!!) + public virtual bool HasClaim(string type, string value) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(value); + foreach (Claim claim in Claims) { if (claim != null @@ -662,8 +691,10 @@ public virtual bool HasClaim(string type!!, string value!!) /// /// a pointing to a . /// if 'reader' is null. - private void Initialize(BinaryReader reader!!) + private void Initialize(BinaryReader reader) { + ArgumentNullException.ThrowIfNull(reader); + SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 0; int numPropertiesToRead = reader.ReadInt32(); @@ -740,8 +771,10 @@ private void Initialize(BinaryReader reader!!) /// /// the that points at the claim. /// a new . - protected virtual Claim CreateClaim(BinaryReader reader!!) + protected virtual Claim CreateClaim(BinaryReader reader) { + ArgumentNullException.ThrowIfNull(reader); + return new Claim(reader, this); } @@ -761,8 +794,10 @@ public virtual void WriteTo(BinaryWriter writer) /// the to use for data storage. /// additional data provided by derived type. /// if 'writer' is null. - protected virtual void WriteTo(BinaryWriter writer!!, byte[]? userData) + protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) { + ArgumentNullException.ThrowIfNull(writer); + int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; if (_authenticationType != null) diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs index 59d4b794abf131..f13d91a6b2e27a 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsPrincipal.cs @@ -52,8 +52,10 @@ protected ClaimsPrincipal(SerializationInfo info, StreamingContext context) /// /// This method iterates through the collection of ClaimsIdentities and chooses an identity as the primary. /// - private static ClaimsIdentity? SelectPrimaryIdentity(IEnumerable identities!!) + private static ClaimsIdentity? SelectPrimaryIdentity(IEnumerable identities) { + ArgumentNullException.ThrowIfNull(identities); + foreach (ClaimsIdentity identity in identities) { if (identity != null) @@ -101,8 +103,10 @@ public ClaimsPrincipal() /// /// the subjects in the principal. /// if 'identities' is null. - public ClaimsPrincipal(IEnumerable identities!!) + public ClaimsPrincipal(IEnumerable identities) { + ArgumentNullException.ThrowIfNull(identities); + _identities.AddRange(identities); } @@ -111,8 +115,10 @@ public ClaimsPrincipal(IEnumerable identities!!) /// /// representing the subject in the principal. /// if 'identity' is null. - public ClaimsPrincipal(IIdentity identity!!) + public ClaimsPrincipal(IIdentity identity) { + ArgumentNullException.ThrowIfNull(identity); + if (identity is ClaimsIdentity ci) { _identities.Add(ci); @@ -128,8 +134,10 @@ public ClaimsPrincipal(IIdentity identity!!) /// /// used to form this instance. /// if 'principal' is null. - public ClaimsPrincipal(IPrincipal principal!!) + public ClaimsPrincipal(IPrincipal principal) { + ArgumentNullException.ThrowIfNull(principal); + // // If IPrincipal is a ClaimsPrincipal add all of the identities // If IPrincipal is not a ClaimsPrincipal, create a new identity from IPrincipal.Identity @@ -154,8 +162,10 @@ public ClaimsPrincipal(IPrincipal principal!!) /// /// a pointing to a . /// if 'reader' is null. - public ClaimsPrincipal(BinaryReader reader!!) + public ClaimsPrincipal(BinaryReader reader) { + ArgumentNullException.ThrowIfNull(reader); + SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesToRead = reader.ReadInt32(); int numPropertiesRead = 0; @@ -188,8 +198,10 @@ public ClaimsPrincipal(BinaryReader reader!!) /// /// the add. /// if 'identity' is null. - public virtual void AddIdentity(ClaimsIdentity identity!!) + public virtual void AddIdentity(ClaimsIdentity identity) { + ArgumentNullException.ThrowIfNull(identity); + _identities.Add(identity); } @@ -198,8 +210,10 @@ public virtual void AddIdentity(ClaimsIdentity identity!!) /// /// Enumeration of ClaimsIdentities to add. /// if 'identities' is null. - public virtual void AddIdentities(IEnumerable identities!!) + public virtual void AddIdentities(IEnumerable identities) { + ArgumentNullException.ThrowIfNull(identities); + _identities.AddRange(identities); } @@ -245,8 +259,10 @@ public virtual ClaimsPrincipal Clone() /// the that points at the claim. /// if 'reader' is null. /// a new . - protected virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader!!) + protected virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader) { + ArgumentNullException.ThrowIfNull(reader); + return new ClaimsIdentity(reader); } @@ -269,15 +285,21 @@ public static ClaimsPrincipal? Current /// A of matched claims. /// Each is called. . /// if 'match' is null. - public virtual IEnumerable FindAll(Predicate match!!) + public virtual IEnumerable FindAll(Predicate match) { - foreach (ClaimsIdentity identity in Identities) + ArgumentNullException.ThrowIfNull(match); + return Core(match); + + IEnumerable Core(Predicate match) { - if (identity != null) + foreach (ClaimsIdentity identity in Identities) { - foreach (Claim claim in identity.FindAll(match)) + if (identity != null) { - yield return claim; + foreach (Claim claim in identity.FindAll(match)) + { + yield return claim; + } } } } @@ -290,15 +312,21 @@ public virtual IEnumerable FindAll(Predicate match!!) /// A of matched claims. /// Each is called. . /// if 'type' is null. - public virtual IEnumerable FindAll(string type!!) + public virtual IEnumerable FindAll(string type) { - foreach (ClaimsIdentity identity in Identities) + ArgumentNullException.ThrowIfNull(type); + return Core(type); + + IEnumerable Core(string type) { - if (identity != null) + foreach (ClaimsIdentity identity in Identities) { - foreach (Claim claim in identity.FindAll(type)) + if (identity != null) { - yield return claim; + foreach (Claim claim in identity.FindAll(type)) + { + yield return claim; + } } } } @@ -311,8 +339,10 @@ public virtual IEnumerable FindAll(string type!!) /// A , null if nothing matches. /// Each is called. . /// if 'match' is null. - public virtual Claim? FindFirst(Predicate match!!) + public virtual Claim? FindFirst(Predicate match) { + ArgumentNullException.ThrowIfNull(match); + Claim? claim = null; foreach (ClaimsIdentity identity in Identities) @@ -337,8 +367,10 @@ public virtual IEnumerable FindAll(string type!!) /// A , null if nothing matches. /// Each is called. . /// if 'type' is null. - public virtual Claim? FindFirst(string type!!) + public virtual Claim? FindFirst(string type) { + ArgumentNullException.ThrowIfNull(type); + Claim? claim = null; for (int i = 0; i < _identities.Count; i++) @@ -363,8 +395,10 @@ public virtual IEnumerable FindAll(string type!!) /// true if a claim is found, false otherwise. /// Each is called. . /// if 'match' is null. - public virtual bool HasClaim(Predicate match!!) + public virtual bool HasClaim(Predicate match) { + ArgumentNullException.ThrowIfNull(match); + for (int i = 0; i < _identities.Count; i++) { if (_identities[i] != null) @@ -388,8 +422,11 @@ public virtual bool HasClaim(Predicate match!!) /// Each is called. . /// if 'type' is null. /// if 'value' is null. - public virtual bool HasClaim(string type!!, string value!!) + public virtual bool HasClaim(string type, string value) { + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; i < _identities.Count; i++) { if (_identities[i] != null) @@ -471,8 +508,10 @@ public virtual void WriteTo(BinaryWriter writer) /// the to use for data storage. /// additional data provided by derived type. /// if 'writer' is null. - protected virtual void WriteTo(BinaryWriter writer!!, byte[]? userData) + protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) { + ArgumentNullException.ThrowIfNull(writer); + int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; if (_identities.Count > 0) diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs index 13e034120e47b3..a5e627c7c99488 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericIdentity.cs @@ -11,16 +11,21 @@ public class GenericIdentity : ClaimsIdentity private readonly string m_name; private readonly string m_type; - public GenericIdentity(string name!!) + public GenericIdentity(string name) { + ArgumentNullException.ThrowIfNull(name); + m_name = name; m_type = ""; AddNameClaim(); } - public GenericIdentity(string name!!, string type!!) + public GenericIdentity(string name, string type) { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(type); + m_name = name; m_type = type; diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs index 1cfeabf5a5677a..a4441b8a31803a 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/GenericPrincipal.cs @@ -12,8 +12,10 @@ public class GenericPrincipal : ClaimsPrincipal private readonly IIdentity m_identity; private readonly string[]? m_roles; - public GenericPrincipal(IIdentity identity!!, string[]? roles) + public GenericPrincipal(IIdentity identity, string[]? roles) { + ArgumentNullException.ThrowIfNull(identity); + m_identity = identity; if (roles != null) { diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs index f1dfbda6d24059..2671e8c2dd0cb6 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs @@ -53,8 +53,8 @@ public ReadOnlyMemory? Content } } - public static CoseSign1Message DecodeSign1(byte[] cborPayload!!) - => DecodeCoseSign1Core(new CborReader(cborPayload)); + public static CoseSign1Message DecodeSign1(byte[] cborPayload) + => DecodeCoseSign1Core(new CborReader(cborPayload ?? throw new ArgumentNullException(nameof(cborPayload)))); public static CoseSign1Message DecodeSign1(ReadOnlySpan cborPayload) { diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs index b36498c1ee90b3..7a82d78494322b 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; @@ -21,16 +21,43 @@ internal CoseSign1Message(CoseHeaderMap protectedHeader, CoseHeaderMap unprotect : base(protectedHeader, unprotectedHeader, content, signature, protectedHeaderAsBstr) { } [UnsupportedOSPlatform("browser")] - public static byte[] Sign(byte[] content!!, AsymmetricAlgorithm key!!, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, bool isDetached = false) - => SignCore(content.AsSpan(), null, key, hashAlgorithm, GetKeyType(key), protectedHeaders, unprotectedHeaders, isDetached); + public static byte[] Sign(byte[] content, AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, bool isDetached = false) + { + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + + return SignCore(content.AsSpan(), null, key, hashAlgorithm, GetKeyType(key), protectedHeaders, unprotectedHeaders, isDetached); + } [UnsupportedOSPlatform("browser")] - public static byte[] Sign(ReadOnlySpan content, AsymmetricAlgorithm key!!, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, bool isDetached = false) - => SignCore(content, null, key, hashAlgorithm, GetKeyType(key), protectedHeaders, unprotectedHeaders, isDetached); + public static byte[] Sign(ReadOnlySpan content, AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, bool isDetached = false) + { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + + return SignCore(content, null, key, hashAlgorithm, GetKeyType(key), protectedHeaders, unprotectedHeaders, isDetached); + } [UnsupportedOSPlatform("browser")] - public static byte[] Sign(Stream detachedContent!!, AsymmetricAlgorithm key!!, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null) + public static byte[] Sign(Stream detachedContent, AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null) { + if (detachedContent is null) + { + throw new ArgumentNullException(nameof(detachedContent)); + } + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (!detachedContent.CanRead) { throw new ArgumentException(SR.Sign1ArgumentStreamNotReadable, nameof(detachedContent)); @@ -80,13 +107,22 @@ internal static byte[] SignCore( [UnsupportedOSPlatform("browser")] public static Task SignAsync( - Stream detachedContent!!, - AsymmetricAlgorithm key!!, + Stream detachedContent, + AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, CancellationToken cancellationToken = default) { + if (detachedContent is null) + { + throw new ArgumentNullException(nameof(detachedContent)); + } + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (!detachedContent.CanRead) { throw new ArgumentException(SR.Sign1ArgumentStreamNotReadable, nameof(detachedContent)); @@ -127,13 +163,18 @@ private static async Task SignAsyncCore( public static bool TrySign( ReadOnlySpan content, Span destination, - AsymmetricAlgorithm key!!, + AsymmetricAlgorithm key, HashAlgorithmName hashAlgorithm, out int bytesWritten, CoseHeaderMap? protectedHeaders = null, CoseHeaderMap? unprotectedHeaders = null, bool isDetached = false) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + KeyType keyType = GetKeyType(key); ValidateBeforeSign(protectedHeaders, unprotectedHeaders, keyType, hashAlgorithm, out int? algHeaderValueToSlip); @@ -277,8 +318,13 @@ private static void WriteSignature(Span buffer, IncrementalHash hasher, Cb } [UnsupportedOSPlatform("browser")] - public bool Verify(AsymmetricAlgorithm key!!) + public bool Verify(AsymmetricAlgorithm key) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (_content == null) { throw new CryptographicException(SR.Sign1VerifyContentWasDetached); @@ -288,8 +334,17 @@ public bool Verify(AsymmetricAlgorithm key!!) } [UnsupportedOSPlatform("browser")] - public bool Verify(AsymmetricAlgorithm key!!, byte[] content!!) + public bool Verify(AsymmetricAlgorithm key, byte[] content) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + if (_content != null) { throw new CryptographicException(SR.Sign1VerifyContentWasEmbedded); @@ -299,8 +354,13 @@ public bool Verify(AsymmetricAlgorithm key!!, byte[] content!!) } [UnsupportedOSPlatform("browser")] - public bool Verify(AsymmetricAlgorithm key!!, ReadOnlySpan content) + public bool Verify(AsymmetricAlgorithm key, ReadOnlySpan content) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (_content != null) { throw new CryptographicException(SR.Sign1VerifyContentWasEmbedded); @@ -310,8 +370,17 @@ public bool Verify(AsymmetricAlgorithm key!!, ReadOnlySpan content) } [UnsupportedOSPlatform("browser")] - public bool Verify(AsymmetricAlgorithm key!!, Stream detachedContent!!) + public bool Verify(AsymmetricAlgorithm key, Stream detachedContent) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (detachedContent is null) + { + throw new ArgumentNullException(nameof(detachedContent)); + } + if (_content != null) { throw new CryptographicException(SR.Sign1VerifyContentWasEmbedded); @@ -372,8 +441,17 @@ private bool VerifyCore(AsymmetricAlgorithm key, ReadOnlySpan contentBytes } [UnsupportedOSPlatform("browser")] - public Task VerifyAsync(AsymmetricAlgorithm key!!, Stream detachedContent!!, CancellationToken cancellationToken = default) + public Task VerifyAsync(AsymmetricAlgorithm key, Stream detachedContent, CancellationToken cancellationToken = default) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (detachedContent is null) + { + throw new ArgumentNullException(nameof(detachedContent)); + } + if (_content != null) { throw new CryptographicException(SR.Sign1VerifyContentWasEmbedded); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs index bdd093252bb6ec..8e5e3090901b97 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/CryptographicAttributeObjectCollection.cs @@ -23,13 +23,23 @@ public CryptographicAttributeObjectCollection(CryptographicAttributeObject attri _list.Add(attribute); } - public int Add(AsnEncodedData asnEncodedData!!) + public int Add(AsnEncodedData asnEncodedData) { + if (asnEncodedData is null) + { + throw new ArgumentNullException(nameof(asnEncodedData)); + } + return Add(new CryptographicAttributeObject(asnEncodedData.Oid!, new AsnEncodedDataCollection(asnEncodedData))); } - public int Add(CryptographicAttributeObject attribute!!) + public int Add(CryptographicAttributeObject attribute) { + if (attribute is null) + { + throw new ArgumentNullException(nameof(attribute)); + } + // // Merge with existing attribute, if already existed, else add as new. // @@ -71,8 +81,13 @@ internal void AddWithoutMerge(CryptographicAttributeObject attribute) _list.Add(attribute); } - public void Remove(CryptographicAttributeObject attribute!!) + public void Remove(CryptographicAttributeObject attribute) { + if (attribute is null) + { + throw new ArgumentNullException(nameof(attribute)); + } + _list.Remove(attribute); } @@ -118,8 +133,13 @@ IEnumerator IEnumerable.GetEnumerator() return new CryptographicAttributeObjectEnumerator(this); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -134,8 +154,13 @@ void ICollection.CopyTo(Array array!!, int index) } } - public void CopyTo(CryptographicAttributeObject[] array!!, int index) + public void CopyTo(CryptographicAttributeObject[] array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); if (index > array.Length - Count) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs index 9fa5dcc89fabe4..034b1099d752aa 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipient.cs @@ -19,9 +19,14 @@ public CmsRecipient(X509Certificate2 certificate) #else public #endif - CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding!!) + CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding) : this(certificate) { + if (rsaEncryptionPadding is null) + { + throw new ArgumentNullException(nameof(rsaEncryptionPadding)); + } + ValidateRSACertificate(certificate); RSAEncryptionPadding = rsaEncryptionPadding; } @@ -31,15 +36,25 @@ public CmsRecipient(X509Certificate2 certificate) #else public #endif - CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding!!) + CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding) : this(recipientIdentifierType, certificate) { + if (rsaEncryptionPadding is null) + { + throw new ArgumentNullException(nameof(rsaEncryptionPadding)); + } + ValidateRSACertificate(certificate); RSAEncryptionPadding = rsaEncryptionPadding; } - public CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate!!) + public CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate) { + if (certificate is null) + { + throw new ArgumentNullException(nameof(certificate)); + } + switch (recipientIdentifierType) { case SubjectIdentifierType.Unknown: diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs index aa84503383a7fb..f4745b8b35ec00 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsRecipientCollection.cs @@ -53,15 +53,25 @@ public int Count } } - public int Add(CmsRecipient recipient!!) + public int Add(CmsRecipient recipient) { + if (recipient is null) + { + throw new ArgumentNullException(nameof(recipient)); + } + int indexOfNewItem = _recipients.Count; _recipients.Add(recipient); return indexOfNewItem; } - public void Remove(CmsRecipient recipient!!) + public void Remove(CmsRecipient recipient) { + if (recipient is null) + { + throw new ArgumentNullException(nameof(recipient)); + } + _recipients.Remove(recipient); } @@ -75,8 +85,13 @@ IEnumerator IEnumerable.GetEnumerator() return new CmsRecipientEnumerator(this); } - public void CopyTo(Array array!!, int index) + public void CopyTo(Array array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -91,8 +106,13 @@ public void CopyTo(Array array!!, int index) } } - public void CopyTo(CmsRecipient[] array!!, int index) + public void CopyTo(CmsRecipient[] array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); if (index > array.Length - Count) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs index cdc8659b487f62..50d1940081f41e 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/ContentInfo.cs @@ -19,8 +19,17 @@ public ContentInfo(byte[] content) { } - public ContentInfo(Oid contentType!!, byte[] content!!) + public ContentInfo(Oid contentType, byte[] content) { + if (contentType is null) + { + throw new ArgumentNullException(nameof(contentType)); + } + if (content is null) + { + throw new ArgumentNullException(nameof(content)); + } + ContentType = contentType; Content = content; } @@ -29,8 +38,13 @@ public ContentInfo(Oid contentType!!, byte[] content!!) public byte[] Content { get; } - public static Oid GetContentType(byte[] encodedMessage!!) + public static Oid GetContentType(byte[] encodedMessage) { + if (encodedMessage is null) + { + throw new ArgumentNullException(nameof(encodedMessage)); + } + return PkcsPal.Instance.GetEncodedMessageType(encodedMessage); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs index f33f8c2b36a8e0..0fab983af14d2f 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/EnvelopedCms.cs @@ -25,8 +25,17 @@ public EnvelopedCms(ContentInfo contentInfo) { } - public EnvelopedCms(ContentInfo contentInfo!!, AlgorithmIdentifier encryptionAlgorithm!!) + public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) { + if (contentInfo is null) + { + throw new ArgumentNullException(nameof(contentInfo)); + } + if (encryptionAlgorithm is null) + { + throw new ArgumentNullException(nameof(encryptionAlgorithm)); + } + Version = 0; // It makes little sense to ask for a version before you've decoded, but since the .NET Framework returns 0 in that case, we will too. ContentInfo = contentInfo; ContentEncryptionAlgorithm = encryptionAlgorithm; @@ -79,13 +88,23 @@ public RecipientInfoCollection RecipientInfos // // Encrypt() overloads. Senders invoke this to encrypt and encode a CMS. Afterward, invoke the Encode() method to retrieve the actual encoding. // - public void Encrypt(CmsRecipient recipient!!) + public void Encrypt(CmsRecipient recipient) { + if (recipient is null) + { + throw new ArgumentNullException(nameof(recipient)); + } + Encrypt(new CmsRecipientCollection(recipient)); } - public void Encrypt(CmsRecipientCollection recipients!!) + public void Encrypt(CmsRecipientCollection recipients) { + if (recipients is null) + { + throw new ArgumentNullException(nameof(recipients)); + } + // .NET Framework compat note: Unlike the desktop, we don't provide a free UI to select the recipient. The app must give it to us programmatically. if (recipients.Count == 0) throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoRecipients); @@ -113,8 +132,13 @@ public byte[] Encode() // // Recipients invoke Decode() to turn the on-the-wire representation into a usable EnvelopedCms instance. Next step is to call Decrypt(). // - public void Decode(byte[] encodedMessage!!) + public void Decode(byte[] encodedMessage) { + if (encodedMessage is null) + { + throw new ArgumentNullException(nameof(encodedMessage)); + } + Decode(new ReadOnlySpan(encodedMessage)); } @@ -161,23 +185,47 @@ public void Decrypt() DecryptContent(RecipientInfos, null); } - public void Decrypt(RecipientInfo recipientInfo!!) + public void Decrypt(RecipientInfo recipientInfo) { + if (recipientInfo is null) + { + throw new ArgumentNullException(nameof(recipientInfo)); + } + DecryptContent(new RecipientInfoCollection(recipientInfo), null); } - public void Decrypt(RecipientInfo recipientInfo!!, X509Certificate2Collection extraStore!!) + public void Decrypt(RecipientInfo recipientInfo, X509Certificate2Collection extraStore) { + if (recipientInfo is null) + { + throw new ArgumentNullException(nameof(recipientInfo)); + } + if (extraStore is null) + { + throw new ArgumentNullException(nameof(extraStore)); + } + DecryptContent(new RecipientInfoCollection(recipientInfo), extraStore); } - public void Decrypt(X509Certificate2Collection extraStore!!) + public void Decrypt(X509Certificate2Collection extraStore) { + if (extraStore is null) + { + throw new ArgumentNullException(nameof(extraStore)); + } + DecryptContent(RecipientInfos, extraStore); } - public void Decrypt(RecipientInfo recipientInfo!!, AsymmetricAlgorithm? privateKey) + public void Decrypt(RecipientInfo recipientInfo, AsymmetricAlgorithm? privateKey) { + if (recipientInfo is null) + { + throw new ArgumentNullException(nameof(recipientInfo)); + } + CheckStateForDecryption(); X509Certificate2Collection extraStore = new X509Certificate2Collection(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs index 1f3c77bb93ba6a..008cebd02f2c77 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs @@ -30,10 +30,19 @@ public void AddSafeContentsEncrypted( } public void AddSafeContentsEncrypted( - Pkcs12SafeContents safeContents!!, + Pkcs12SafeContents safeContents, ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + if (safeContents is null) + { + throw new ArgumentNullException(nameof(safeContents)); + } + if (pbeParameters is null) + { + throw new ArgumentNullException(nameof(pbeParameters)); + } + if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) @@ -74,10 +83,19 @@ public void AddSafeContentsEncrypted( } public void AddSafeContentsEncrypted( - Pkcs12SafeContents safeContents!!, + Pkcs12SafeContents safeContents, ReadOnlySpan password, - PbeParameters pbeParameters!!) + PbeParameters pbeParameters) { + if (safeContents is null) + { + throw new ArgumentNullException(nameof(safeContents)); + } + if (pbeParameters is null) + { + throw new ArgumentNullException(nameof(pbeParameters)); + } + if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) @@ -105,8 +123,13 @@ public void AddSafeContentsEncrypted( }); } - public void AddSafeContentsUnencrypted(Pkcs12SafeContents safeContents!!) + public void AddSafeContentsUnencrypted(Pkcs12SafeContents safeContents) { + if (safeContents is null) + { + throw new ArgumentNullException(nameof(safeContents)); + } + if (IsSealed) throw new InvalidOperationException(SR.Cryptography_Pkcs12_PfxIsSealed); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs index 05631d3d26f279..e0a2108f012bf2 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12CertBag.cs @@ -82,8 +82,13 @@ public X509Certificate2 GetCertificate() return new X509Certificate2(PkcsHelpers.DecodeOctetString(_decoded.CertValue)); } - private static byte[] EncodeBagValue(Oid certificateType!!, ReadOnlyMemory encodedCertificate) + private static byte[] EncodeBagValue(Oid certificateType, ReadOnlyMemory encodedCertificate) { + if (certificateType is null) + { + throw new ArgumentNullException(nameof(certificateType)); + } + if (certificateType.Value == null) throw new CryptographicException(SR.Argument_InvalidOidValue); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs index d5a9412a78986b..e2f7666b9bab69 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12SafeContents.cs @@ -55,8 +55,13 @@ internal Pkcs12SafeContents(ContentInfoAsn contentInfoAsn) } } - public void AddSafeBag(Pkcs12SafeBag safeBag!!) + public void AddSafeBag(Pkcs12SafeBag safeBag) { + if (safeBag is null) + { + throw new ArgumentNullException(nameof(safeBag)); + } + if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -68,8 +73,13 @@ public void AddSafeBag(Pkcs12SafeBag safeBag!!) _bags.Add(safeBag); } - public Pkcs12CertBag AddCertificate(X509Certificate2 certificate!!) + public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) { + if (certificate is null) + { + throw new ArgumentNullException(nameof(certificate)); + } + if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -78,8 +88,13 @@ public Pkcs12CertBag AddCertificate(X509Certificate2 certificate!!) return bag; } - public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key!!) + public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -89,8 +104,13 @@ public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key!!) return bag; } - public Pkcs12SafeContentsBag AddNestedContents(Pkcs12SafeContents safeContents!!) + public Pkcs12SafeContentsBag AddNestedContents(Pkcs12SafeContents safeContents) { + if (safeContents is null) + { + throw new ArgumentNullException(nameof(safeContents)); + } + if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents)); if (IsReadOnly) @@ -114,10 +134,15 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( } public Pkcs12ShroudedKeyBag AddShroudedKey( - AsymmetricAlgorithm key!!, + AsymmetricAlgorithm key, ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -140,10 +165,15 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( } public Pkcs12ShroudedKeyBag AddShroudedKey( - AsymmetricAlgorithm key!!, + AsymmetricAlgorithm key, ReadOnlySpan password, PbeParameters pbeParameters) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -153,8 +183,13 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( return bag; } - public Pkcs12SecretBag AddSecret(Oid secretType!!, ReadOnlyMemory secretValue) + public Pkcs12SecretBag AddSecret(Oid secretType, ReadOnlyMemory secretValue) { + if (secretType is null) + { + throw new ArgumentNullException(nameof(secretType)); + } + // Read to ensure that there is precisely one legally encoded value. PkcsHelpers.EnsureSingleBerValue(secretValue.Span); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs index 5d97f99be065d3..d1bf0b69932ee9 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs8PrivateKeyInfo.cs @@ -17,11 +17,16 @@ public sealed class Pkcs8PrivateKeyInfo public ReadOnlyMemory PrivateKeyBytes { get; } public Pkcs8PrivateKeyInfo( - Oid algorithmId!!, + Oid algorithmId, ReadOnlyMemory? algorithmParameters, ReadOnlyMemory privateKey, bool skipCopies = false) { + if (algorithmId is null) + { + throw new ArgumentNullException(nameof(algorithmId)); + } + if (algorithmParameters?.Length > 0) { // Read to ensure that there is precisely one legally encoded value. @@ -48,8 +53,13 @@ private Pkcs8PrivateKeyInfo( Attributes = attributes; } - public static Pkcs8PrivateKeyInfo Create(AsymmetricAlgorithm privateKey!!) + public static Pkcs8PrivateKeyInfo Create(AsymmetricAlgorithm privateKey) { + if (privateKey is null) + { + throw new ArgumentNullException(nameof(privateKey)); + } + byte[] pkcs8 = privateKey.ExportPkcs8PrivateKey(); return Decode(pkcs8, out _, skipCopy: true); } @@ -88,8 +98,13 @@ public byte[] Encode() return writer.Encode(); } - public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters!!) + public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) { + if (pbeParameters is null) + { + throw new ArgumentNullException(nameof(pbeParameters)); + } + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -102,8 +117,13 @@ public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters!! } } - public byte[] Encrypt(ReadOnlySpan passwordBytes, PbeParameters pbeParameters!!) + public byte[] Encrypt(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { + if (pbeParameters is null) + { + throw new ArgumentNullException(nameof(pbeParameters)); + } + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -122,10 +142,15 @@ public bool TryEncode(Span destination, out int bytesWritten) public bool TryEncrypt( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + if (pbeParameters is null) + { + throw new ArgumentNullException(nameof(pbeParameters)); + } + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -138,10 +163,15 @@ public bool TryEncrypt( public bool TryEncrypt( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + if (pbeParameters is null) + { + throw new ArgumentNullException(nameof(pbeParameters)); + } + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs index e9810d2af658db..0103d88b17a723 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs @@ -56,8 +56,13 @@ internal Pkcs9AttributeObject(Oid oid) } } - public override void CopyFrom(AsnEncodedData asnEncodedData!!) + public override void CopyFrom(AsnEncodedData asnEncodedData) { + if (asnEncodedData is null) + { + throw new ArgumentNullException(nameof(asnEncodedData)); + } + if (!(asnEncodedData is Pkcs9AttributeObject)) throw new ArgumentException(SR.Cryptography_Pkcs9_AttributeMismatch); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs index 617fcb304e961d..b55f97685c5c05 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentDescription.cs @@ -62,8 +62,13 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) return octets.OctetStringToUnicode(); } - private static byte[] Encode(string documentDescription!!) + private static byte[] Encode(string documentDescription) { + if (documentDescription is null) + { + throw new ArgumentNullException(nameof(documentDescription)); + } + byte[] octets = documentDescription.UnicodeToOctetString(); return PkcsHelpers.EncodeOctetString(octets); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs index 5344eb70c3f267..5135511d33b3d0 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9DocumentName.cs @@ -62,8 +62,13 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) return octets.OctetStringToUnicode(); } - private static byte[] Encode(string documentName!!) + private static byte[] Encode(string documentName) { + if (documentName is null) + { + throw new ArgumentNullException(nameof(documentName)); + } + byte[] octets = documentName.UnicodeToOctetString(); return PkcsHelpers.EncodeOctetString(octets); } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs index d4058866d3c759..7c6dc6248213c0 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/RecipientInfoCollection.cs @@ -54,8 +54,13 @@ IEnumerator IEnumerable.GetEnumerator() return ((RecipientInfoCollection)this).GetEnumerator(); } - public void CopyTo(Array array!!, int index) + public void CopyTo(Array array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -69,8 +74,13 @@ public void CopyTo(Array array!!, int index) } } - public void CopyTo(RecipientInfo[] array!!, int index) + public void CopyTo(RecipientInfo[] array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess); _recipientInfos.CopyTo(array, index); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs index e834302c7b3aa7..23df99670fcbbf 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs @@ -162,13 +162,18 @@ public bool TryEncode(Span destination, out int bytesWritten) } public static Rfc3161TimestampRequest CreateFromSignerInfo( - SignerInfo signerInfo!!, + SignerInfo signerInfo, HashAlgorithmName hashAlgorithm, Oid? requestedPolicyId = null, ReadOnlyMemory? nonce = null, bool requestSignerCertificates = false, X509ExtensionCollection? extensions = null) { + if (signerInfo is null) + { + throw new ArgumentNullException(nameof(signerInfo)); + } + // https://tools.ietf.org/html/rfc3161, Appendix A. // // The value of messageImprint field within TimeStampToken shall be a diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs index b5773082db3706..60cae7ea570557 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampToken.cs @@ -120,10 +120,15 @@ public bool VerifySignatureForHash( public bool VerifySignatureForHash( ReadOnlySpan hash, - Oid hashAlgorithmId!!, + Oid hashAlgorithmId, [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { + if (hashAlgorithmId is null) + { + throw new ArgumentNullException(nameof(hashAlgorithmId)); + } + signerCertificate = null; X509Certificate2? cert = GetSignerCertificate(extraCandidates); @@ -147,10 +152,15 @@ public bool VerifySignatureForHash( } public bool VerifySignatureForSignerInfo( - SignerInfo signerInfo!!, + SignerInfo signerInfo, [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { + if (signerInfo is null) + { + throw new ArgumentNullException(nameof(signerInfo)); + } + return VerifySignatureForData( signerInfo.GetSignatureMemory().Span, out signerCertificate, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs index a1e54d08e9592e..f40c32357f1ed9 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampTokenInfo.cs @@ -312,8 +312,8 @@ private static bool TryDecode( } private static byte[] Encode( - Oid policyId!!, - Oid hashAlgorithmId!!, + Oid policyId, + Oid hashAlgorithmId, ReadOnlyMemory messageHash, ReadOnlyMemory serialNumber, DateTimeOffset timestamp, @@ -323,6 +323,15 @@ private static byte[] Encode( ReadOnlyMemory? tsaName, X509ExtensionCollection? extensions) { + if (policyId is null) + { + throw new ArgumentNullException(nameof(policyId)); + } + if (hashAlgorithmId is null) + { + throw new ArgumentNullException(nameof(hashAlgorithmId)); + } + var tstInfo = new Rfc3161TstInfo { // The only legal value as of 2017. diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs index 459411ce51d40b..8a88fb2b482bee 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs @@ -41,8 +41,13 @@ public sealed partial class SignedCms public ContentInfo ContentInfo { get; private set; } public bool Detached { get; private set; } - public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo!!, bool detached) + public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached) { + if (contentInfo is null) + { + throw new ArgumentNullException(nameof(contentInfo)); + } + if (contentInfo.Content == null) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "contentInfo.Content"), nameof(contentInfo)); @@ -157,8 +162,13 @@ public byte[] Encode() } } - public void Decode(byte[] encodedMessage!!) + public void Decode(byte[] encodedMessage) { + if (encodedMessage is null) + { + throw new ArgumentNullException(nameof(encodedMessage)); + } + Decode(new ReadOnlySpan(encodedMessage)); } @@ -295,8 +305,13 @@ internal static ReadOnlyMemory GetContent( public void ComputeSignature(CmsSigner signer) => ComputeSignature(signer, true); - public void ComputeSignature(CmsSigner signer!!, bool silent) + public void ComputeSignature(CmsSigner signer, bool silent) { + if (signer is null) + { + throw new ArgumentNullException(nameof(signer)); + } + // While it shouldn't be possible to change the length of ContentInfo.Content // after it's built, use the property at this stage, then use the saved value // (if applicable) after this point. @@ -399,8 +414,13 @@ public void RemoveSignature(int index) UpdateMetadata(); } - public void RemoveSignature(SignerInfo signerInfo!!) + public void RemoveSignature(SignerInfo signerInfo) { + if (signerInfo is null) + { + throw new ArgumentNullException(nameof(signerInfo)); + } + int idx = SignerInfos.FindIndexForSigner(signerInfo); if (idx < 0) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs index 144a6e8e554f2f..a677fcd1fc4b94 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs @@ -435,8 +435,13 @@ public void RemoveCounterSignature(int index) } } - public void RemoveCounterSignature(SignerInfo counterSignerInfo!!) + public void RemoveCounterSignature(SignerInfo counterSignerInfo) { + if (counterSignerInfo is null) + { + throw new ArgumentNullException(nameof(counterSignerInfo)); + } + SignerInfoCollection docSigners = _document.SignerInfos; int index = docSigners.FindIndexForSigner(this); @@ -459,8 +464,13 @@ public void RemoveCounterSignature(SignerInfo counterSignerInfo!!) public void CheckSignature(bool verifySignatureOnly) => CheckSignature(new X509Certificate2Collection(), verifySignatureOnly); - public void CheckSignature(X509Certificate2Collection extraStore!!, bool verifySignatureOnly) + public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly) { + if (extraStore is null) + { + throw new ArgumentNullException(nameof(extraStore)); + } + X509Certificate2? certificate = Certificate; if (certificate == null) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs index 0c335a10aa3e2c..64e1bf2f2bb883 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfoCollection.cs @@ -51,8 +51,13 @@ public SignerInfo this[int index] public SignerInfoEnumerator GetEnumerator() => new SignerInfoEnumerator(this); IEnumerator IEnumerable.GetEnumerator() => new SignerInfoEnumerator(this); - public void CopyTo(Array array!!, int index) + public void CopyTo(Array array, int index) { + if (array is null) + { + throw new ArgumentNullException(nameof(array)); + } + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0 || index >= array.Length) diff --git a/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs b/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs index 61e40cdde4da18..61bb88a6cbe53f 100644 --- a/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs +++ b/src/libraries/System.Security.Cryptography.ProtectedData/src/System/Security/Cryptography/ProtectedData.cs @@ -14,13 +14,17 @@ public static partial class ProtectedData { private static readonly byte[] s_nonEmpty = new byte[1]; - public static byte[] Protect(byte[] userData!!, byte[]? optionalEntropy, DataProtectionScope scope) + public static byte[] Protect(byte[] userData, byte[]? optionalEntropy, DataProtectionScope scope) { + ArgumentNullException.ThrowIfNull(userData); + return ProtectOrUnprotect(userData, optionalEntropy, scope, protect: true); } - public static byte[] Unprotect(byte[] encryptedData!!, byte[]? optionalEntropy, DataProtectionScope scope) + public static byte[] Unprotect(byte[] encryptedData, byte[]? optionalEntropy, DataProtectionScope scope) { + ArgumentNullException.ThrowIfNull(encryptedData); + return ProtectOrUnprotect(encryptedData, optionalEntropy, scope, protect: false); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs index 5c9cc7e70a3ce7..a42e1b1770307d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalXml.cs @@ -17,8 +17,13 @@ internal sealed class CanonicalXml // private static string defaultXPathWithComments = "(//. | //@* | //namespace::*)"; // private static string defaultXPathWithComments = "(//. | //@* | //namespace::*)"; - internal CanonicalXml(Stream inputStream!!, bool includeComments, XmlResolver resolver, string strBaseUri) + internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver resolver, string strBaseUri) { + if (inputStream is null) + { + throw new ArgumentNullException(nameof(inputStream)); + } + _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(Utils.PreProcessStreamInput(inputStream, resolver, strBaseUri)); @@ -26,16 +31,26 @@ internal CanonicalXml(Stream inputStream!!, bool includeComments, XmlResolver re } internal CanonicalXml(XmlDocument document, XmlResolver resolver) : this(document, resolver, false) { } - internal CanonicalXml(XmlDocument document!!, XmlResolver resolver, bool includeComments) + internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeComments) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(new XmlNodeReader(document)); _ancMgr = new C14NAncestralNamespaceContextManager(); } - internal CanonicalXml(XmlNodeList nodeList!!, XmlResolver resolver, bool includeComments) + internal CanonicalXml(XmlNodeList nodeList, XmlResolver resolver, bool includeComments) { + if (nodeList is null) + { + throw new ArgumentNullException(nameof(nodeList)); + } + XmlDocument doc = Utils.GetOwnerDocument(nodeList); if (doc == null) throw new ArgumentException(nameof(nodeList)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs index 62b92652924afc..ae5ff3e1c0c6fc 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CanonicalizationDispatcher.cs @@ -22,8 +22,13 @@ public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition doc } } - public static void WriteGenericNode(XmlNode node!!, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) + public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc) { + if (node is null) + { + throw new ArgumentNullException(nameof(node)); + } + XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode childNode in childNodes) { @@ -43,8 +48,13 @@ public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPo } } - public static void WriteHashGenericNode(XmlNode node!!, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) + public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc) { + if (node is null) + { + throw new ArgumentNullException(nameof(node)); + } + XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode childNode in childNodes) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs index e03b4004a79f97..877c641a4eabd3 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherData.cs @@ -90,8 +90,13 @@ internal XmlElement GetXml(XmlDocument document) return cipherDataElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs index 04e7e8aaa9d8f3..b87286eb7f118b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CipherReference.cs @@ -65,8 +65,13 @@ public override XmlElement GetXml() return referenceElement; } - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + ReferenceType = value.LocalName; string uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); Uri = uri ?? throw new CryptographicException(SR.Cryptography_Xml_UriRequired); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs index f43b5de2c2dfbb..d1b347e1379936 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSAKeyValue.cs @@ -138,8 +138,13 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) /// /// The XML has the incorrect schema or the DSA parameters are invalid. /// - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (value.Name != KeyValueElementName || value.NamespaceURI != SignedXml.XmlDsigNamespaceUrl) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs index 146e1ccffe21dc..83d5929dc68f0c 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DataObject.cs @@ -23,8 +23,13 @@ public DataObject() _elData = new CanonicalXmlNodeList(); } - public DataObject(string id, string mimeType, string encoding, XmlElement data!!) + public DataObject(string id, string mimeType, string encoding, XmlElement data) { + if (data is null) + { + throw new ArgumentNullException(nameof(data)); + } + _id = id; _mimeType = mimeType; _encoding = encoding; @@ -128,8 +133,13 @@ internal XmlElement GetXml(XmlDocument document) return objectElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); _mimeType = Utils.GetAttribute(value, "MimeType", SignedXml.XmlDsigNamespaceUrl); _encoding = Utils.GetAttribute(value, "Encoding", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs index 56e570ff6a84ad..7320dd628118c3 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedData.cs @@ -7,8 +7,13 @@ namespace System.Security.Cryptography.Xml { public sealed class EncryptedData : EncryptedType { - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs index d57eb24215abe3..4d8d96a6b6a447 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs @@ -59,8 +59,13 @@ public void AddReference(KeyReference keyReference) ReferenceList.Add(keyReference); } - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs index 8bbeffb18e99c9..e8e282f0332c9f 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs @@ -103,8 +103,13 @@ internal XmlElement GetXml(XmlDocument document) return referenceElement; } - public virtual void LoadXml(XmlElement value!!) + public virtual void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + ReferenceType = value.LocalName; string uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index 4ea614d17c1fac..65ec076d2e269f 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -178,8 +178,13 @@ public string Recipient // private methods // - private byte[] GetCipherValue(CipherData cipherData!!) + private byte[] GetCipherValue(CipherData cipherData) { + if (cipherData is null) + { + throw new ArgumentNullException(nameof(cipherData)); + } + Stream inputStream = null; if (cipherData.CipherValue != null) @@ -261,8 +266,13 @@ public virtual XmlElement GetIdElement(XmlDocument document, string idValue) } // default behaviour is to look for the IV in the CipherValue - public virtual byte[] GetDecryptionIV(EncryptedData encryptedData!!, string symmetricAlgorithmUri) + public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmetricAlgorithmUri) { + if (encryptedData is null) + { + throw new ArgumentNullException(nameof(encryptedData)); + } + int initBytesSize; // If the Uri is not provided by the application, try to get it from the EncryptionMethod if (symmetricAlgorithmUri == null) @@ -294,8 +304,13 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData!!, string symm // default behaviour is to look for keys defined by an EncryptedKey clause // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping - public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData!!, string symmetricAlgorithmUri) + public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) { + if (encryptedData is null) + { + throw new ArgumentNullException(nameof(encryptedData)); + } + if (encryptedData.KeyInfo == null) return null; IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator(); @@ -376,8 +391,13 @@ public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData!! } // Try to decrypt the EncryptedKey given the key mapping - public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey!!) + public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { + if (encryptedKey is null) + { + throw new ArgumentNullException(nameof(encryptedKey)); + } + if (encryptedKey.KeyInfo == null) return null; @@ -493,8 +513,17 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey!!) // defines a key name mapping. Default behaviour is to require the key object // to be an RSA key or a SymmetricAlgorithm - public void AddKeyNameMapping(string keyName!!, object keyObject!!) + public void AddKeyNameMapping(string keyName, object keyObject) { + if (keyName is null) + { + throw new ArgumentNullException(nameof(keyName)); + } + if (keyObject is null) + { + throw new ArgumentNullException(nameof(keyObject)); + } + if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA)) throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); _keyNameMapping.Add(keyName, keyObject); @@ -507,8 +536,17 @@ public void ClearKeyNameMappings() // Encrypts the given element with the certificate specified. The certificate is added as // an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly. - public EncryptedData Encrypt(XmlElement inputElement!!, X509Certificate2 certificate!!) + public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certificate) { + if (inputElement is null) + { + throw new ArgumentNullException(nameof(inputElement)); + } + if (certificate is null) + { + throw new ArgumentNullException(nameof(certificate)); + } + using (RSA rsaPublicKey = certificate.GetRSAPublicKey()) { if (rsaPublicKey == null) @@ -542,8 +580,17 @@ public EncryptedData Encrypt(XmlElement inputElement!!, X509Certificate2 certifi // Encrypts the given element with the key name specified. A corresponding key name mapping // has to be defined before calling this method. The key name is added as // a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly. - public EncryptedData Encrypt(XmlElement inputElement!!, string keyName!!) + public EncryptedData Encrypt(XmlElement inputElement, string keyName) { + if (inputElement is null) + { + throw new ArgumentNullException(nameof(inputElement)); + } + if (keyName is null) + { + throw new ArgumentNullException(nameof(keyName)); + } + object encryptionKey = null; if (_keyNameMapping != null) encryptionKey = _keyNameMapping[keyName]; @@ -638,8 +685,17 @@ public void DecryptDocument() } // encrypts the supplied arbitrary data - public byte[] EncryptData(byte[] plaintext!!, SymmetricAlgorithm symmetricAlgorithm!!) + public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm) { + if (plaintext is null) + { + throw new ArgumentNullException(nameof(plaintext)); + } + if (symmetricAlgorithm is null) + { + throw new ArgumentNullException(nameof(symmetricAlgorithm)); + } + // save the original symmetric algorithm CipherMode origMode = symmetricAlgorithm.Mode; PaddingMode origPadding = symmetricAlgorithm.Padding; @@ -676,15 +732,33 @@ public byte[] EncryptData(byte[] plaintext!!, SymmetricAlgorithm symmetricAlgori } // encrypts the supplied input element - public byte[] EncryptData(XmlElement inputElement!!, SymmetricAlgorithm symmetricAlgorithm!!, bool content) + public byte[] EncryptData(XmlElement inputElement, SymmetricAlgorithm symmetricAlgorithm, bool content) { + if (inputElement is null) + { + throw new ArgumentNullException(nameof(inputElement)); + } + if (symmetricAlgorithm is null) + { + throw new ArgumentNullException(nameof(symmetricAlgorithm)); + } + byte[] plainText = (content ? _encoding.GetBytes(inputElement.InnerXml) : _encoding.GetBytes(inputElement.OuterXml)); return EncryptData(plainText, symmetricAlgorithm); } // decrypts the supplied EncryptedData - public byte[] DecryptData(EncryptedData encryptedData!!, SymmetricAlgorithm symmetricAlgorithm!!) + public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm) { + if (encryptedData is null) + { + throw new ArgumentNullException(nameof(encryptedData)); + } + if (symmetricAlgorithm is null) + { + throw new ArgumentNullException(nameof(symmetricAlgorithm)); + } + // get the cipher value and decrypt byte[] cipherValue = GetCipherValue(encryptedData.CipherData); @@ -725,8 +799,17 @@ public byte[] DecryptData(EncryptedData encryptedData!!, SymmetricAlgorithm symm } // This method replaces an EncryptedData element with the decrypted sequence of bytes - public void ReplaceData(XmlElement inputElement!!, byte[] decryptedData!!) + public void ReplaceData(XmlElement inputElement, byte[] decryptedData) { + if (inputElement is null) + { + throw new ArgumentNullException(nameof(inputElement)); + } + if (decryptedData is null) + { + throw new ArgumentNullException(nameof(decryptedData)); + } + XmlNode parent = inputElement.ParentNode; if (parent.NodeType == XmlNodeType.Document) { @@ -790,8 +873,17 @@ public void ReplaceData(XmlElement inputElement!!, byte[] decryptedData!!) // // replaces the inputElement with the provided EncryptedData - public static void ReplaceElement(XmlElement inputElement!!, EncryptedData encryptedData!!, bool content) + public static void ReplaceElement(XmlElement inputElement, EncryptedData encryptedData, bool content) { + if (inputElement is null) + { + throw new ArgumentNullException(nameof(inputElement)); + } + if (encryptedData is null) + { + throw new ArgumentNullException(nameof(encryptedData)); + } + // First, get the XML representation of the EncryptedData object XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument); switch (content) @@ -811,8 +903,17 @@ public static void ReplaceElement(XmlElement inputElement!!, EncryptedData encry } // wraps the supplied input key data using the provided symmetric algorithm - public static byte[] EncryptKey(byte[] keyData!!, SymmetricAlgorithm symmetricAlgorithm!!) + public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { + if (keyData is null) + { + throw new ArgumentNullException(nameof(keyData)); + } + if (symmetricAlgorithm is null) + { + throw new ArgumentNullException(nameof(symmetricAlgorithm)); + } + if (symmetricAlgorithm is TripleDES) { // CMS Triple DES Key Wrap @@ -832,8 +933,17 @@ public static byte[] EncryptKey(byte[] keyData!!, SymmetricAlgorithm symmetricAl // encrypts the supplied input key data using an RSA key and specifies whether we want to use OAEP // padding or PKCS#1 v1.5 padding as described in the PKCS specification - public static byte[] EncryptKey(byte[] keyData!!, RSA rsa!!, bool useOAEP) + public static byte[] EncryptKey(byte[] keyData, RSA rsa, bool useOAEP) { + if (keyData is null) + { + throw new ArgumentNullException(nameof(keyData)); + } + if (rsa is null) + { + throw new ArgumentNullException(nameof(rsa)); + } + if (useOAEP) { RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa); @@ -847,8 +957,17 @@ public static byte[] EncryptKey(byte[] keyData!!, RSA rsa!!, bool useOAEP) } // decrypts the supplied wrapped key using the provided symmetric algorithm - public static byte[] DecryptKey(byte[] keyData!!, SymmetricAlgorithm symmetricAlgorithm!!) + public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgorithm) { + if (keyData is null) + { + throw new ArgumentNullException(nameof(keyData)); + } + if (symmetricAlgorithm is null) + { + throw new ArgumentNullException(nameof(symmetricAlgorithm)); + } + if (symmetricAlgorithm is TripleDES) { // CMS Triple DES Key Wrap @@ -867,8 +986,17 @@ public static byte[] DecryptKey(byte[] keyData!!, SymmetricAlgorithm symmetricAl // decrypts the supplied data using an RSA key and specifies whether we want to use OAEP // padding or PKCS#1 v1.5 padding as described in the PKCS specification - public static byte[] DecryptKey(byte[] keyData!!, RSA rsa!!, bool useOAEP) + public static byte[] DecryptKey(byte[] keyData, RSA rsa, bool useOAEP) { + if (keyData is null) + { + throw new ArgumentNullException(nameof(keyData)); + } + if (rsa is null) + { + throw new ArgumentNullException(nameof(rsa)); + } + if (useOAEP) { RSAOAEPKeyExchangeDeformatter rsaDeformatter = new RSAOAEPKeyExchangeDeformatter(rsa); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs index ee19948e7b7773..4ef3bf89a87969 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionMethod.cs @@ -77,8 +77,13 @@ internal XmlElement GetXml(XmlDocument document) return encryptionMethodElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs index e7e0c6131025c6..6077bd264f8c52 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptionProperty.cs @@ -15,8 +15,13 @@ public sealed class EncryptionProperty // We are being lax here as per the spec public EncryptionProperty() { } - public EncryptionProperty(XmlElement elementProperty!!) + public EncryptionProperty(XmlElement elementProperty) { + if (elementProperty is null) + { + throw new ArgumentNullException(nameof(elementProperty)); + } + if (elementProperty.LocalName != "EncryptionProperty" || elementProperty.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); @@ -71,8 +76,13 @@ internal XmlElement GetXml(XmlDocument document) return document.ImportNode(_elemProp, true) as XmlElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (value.LocalName != "EncryptionProperty" || value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs index 723109d4214dee..4a846539bccccd 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcCanonicalXml.cs @@ -12,24 +12,39 @@ internal sealed class ExcCanonicalXml private readonly CanonicalXmlDocument _c14nDoc; private readonly ExcAncestralNamespaceContextManager _ancMgr; - internal ExcCanonicalXml(Stream inputStream!!, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver, string strBaseUri) + internal ExcCanonicalXml(Stream inputStream, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver, string strBaseUri) { + if (inputStream is null) + { + throw new ArgumentNullException(nameof(inputStream)); + } + _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(Utils.PreProcessStreamInput(inputStream, resolver, strBaseUri)); _ancMgr = new ExcAncestralNamespaceContextManager(inclusiveNamespacesPrefixList); } - internal ExcCanonicalXml(XmlDocument document!!, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) + internal ExcCanonicalXml(XmlDocument document, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(new XmlNodeReader(document)); _ancMgr = new ExcAncestralNamespaceContextManager(inclusiveNamespacesPrefixList); } - internal ExcCanonicalXml(XmlNodeList nodeList!!, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) + internal ExcCanonicalXml(XmlNodeList nodeList, bool includeComments, string inclusiveNamespacesPrefixList, XmlResolver resolver) { + if (nodeList is null) + { + throw new ArgumentNullException(nameof(nodeList)); + } + XmlDocument doc = Utils.GetOwnerDocument(nodeList); if (doc == null) throw new ArgumentException(nameof(nodeList)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs index e50050440597b3..d56ce81dd46e3b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfo.cs @@ -58,8 +58,13 @@ internal XmlElement GetXml(XmlDocument xmlDocument) return keyInfoElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlElement keyInfoElement = value; _id = Utils.GetAttribute(keyInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(keyInfoElement, "Id")) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs index 217e3532f85967..7c39edd82a724d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoName.cs @@ -48,8 +48,13 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) return nameElement; } - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlElement nameElement = value; _keyName = nameElement.InnerText.Trim(); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs index 64fbea25761a54..65b6853437e9a4 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoRetrievalMethod.cs @@ -63,8 +63,13 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) return retrievalMethodElement; } - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); _type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs index 5271eb57a3d662..53104e79661c9e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs @@ -39,8 +39,13 @@ public KeyInfoX509Data(X509Certificate cert) AddCertificate(cert); } - public KeyInfoX509Data(X509Certificate cert!!, X509IncludeOption includeOption) + public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption) { + if (cert is null) + { + throw new ArgumentNullException(nameof(cert)); + } + X509Certificate2 certificate = new X509Certificate2(cert); X509ChainElementCollection elements; X509Chain chain; @@ -97,8 +102,13 @@ public ArrayList Certificates get { return _certificates; } } - public void AddCertificate(X509Certificate certificate!!) + public void AddCertificate(X509Certificate certificate) { + if (certificate is null) + { + throw new ArgumentNullException(nameof(certificate)); + } + if (_certificates == null) _certificates = new ArrayList(); @@ -256,8 +266,13 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) return x509DataElement; } - public override void LoadXml(XmlElement element!!) + public override void LoadXml(XmlElement element) { + if (element is null) + { + throw new ArgumentNullException(nameof(element)); + } + XmlNamespaceManager nsm = new XmlNamespaceManager(element.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs index 45817f9184ebce..44b524db5f9956 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAKeyValue.cs @@ -93,8 +93,13 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) /// /// The XML has the incorrect schema or the RSA parameters are invalid. /// - public override void LoadXml(XmlElement value!!) + public override void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (value.LocalName != KeyValueElementName || value.NamespaceURI != SignedXml.XmlDsigNamespaceUrl) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs index 71d7b1bff75d1f..b437eb69df756a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Reference.cs @@ -205,8 +205,13 @@ internal XmlElement GetXml(XmlDocument document) return referenceElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + _id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); _uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); _type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl); @@ -319,8 +324,13 @@ public void LoadXml(XmlElement value!!) _cachedXml = value; } - public void AddTransform(Transform transform!!) + public void AddTransform(Transform transform) { + if (transform is null) + { + throw new ArgumentNullException(nameof(transform)); + } + transform.Reference = this; TransformChain.Add(transform); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs index 6c4dc63a443179..ed01208d6d7384 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ReferenceList.cs @@ -24,8 +24,13 @@ public int Count get { return _references.Count; } } - public int Add(object value!!) + public int Add(object value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -47,8 +52,13 @@ public int IndexOf(object value) return _references.IndexOf(value); } - public void Insert(int index, object value!!) + public void Insert(int index, object value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs index 7d97d7bf88d052..ac6173792e4547 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Signature.cs @@ -133,8 +133,13 @@ internal XmlElement GetXml(XmlDocument document) return signatureElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs index 91ae7009eddffe..6cac8c541c3b0b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedInfo.cs @@ -197,8 +197,13 @@ internal XmlElement GetXml(XmlDocument document) return signedInfoElement; } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + // SignedInfo XmlElement signedInfoElement = value; if (!signedInfoElement.LocalName.Equals("SignedInfo")) @@ -271,8 +276,13 @@ public void LoadXml(XmlElement value!!) _cachedXml = signedInfoElement; } - public void AddReference(Reference reference!!) + public void AddReference(Reference reference) { + if (reference is null) + { + throw new ArgumentNullException(nameof(reference)); + } + reference.SignedXml = SignedXml; _references.Add(reference); } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs index 48b75deec69584..41614db010a839 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs @@ -90,13 +90,23 @@ public SignedXml() Initialize(null); } - public SignedXml(XmlDocument document!!) + public SignedXml(XmlDocument document) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + Initialize(document.DocumentElement); } - public SignedXml(XmlElement elem!!) + public SignedXml(XmlElement elem) { + if (elem is null) + { + throw new ArgumentNullException(nameof(elem)); + } + Initialize(elem); } @@ -207,8 +217,13 @@ public XmlElement GetXml() return m_signature.GetXml(); } - public void LoadXml(XmlElement value!!) + public void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + m_signature.LoadXml(value); if (_context == null) @@ -411,8 +426,13 @@ public void ComputeSignature() m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); } - public void ComputeSignature(KeyedHashAlgorithm macAlg!!) + public void ComputeSignature(KeyedHashAlgorithm macAlg) { + if (macAlg is null) + { + throw new ArgumentNullException(nameof(macAlg)); + } + HMAC hash = macAlg as HMAC; if (hash == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); @@ -981,8 +1001,13 @@ private bool CheckSignatureFormat() return formatValid; } - private bool CheckSignedInfo(AsymmetricAlgorithm key!!) + private bool CheckSignedInfo(AsymmetricAlgorithm key) { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignatureMethod); @@ -1010,8 +1035,13 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key!!) return asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue); } - private bool CheckSignedInfo(KeyedHashAlgorithm macAlg!!) + private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) { + if (macAlg is null) + { + throw new ArgumentNullException(nameof(macAlg)); + } + SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); int signatureLength; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs index a890e4073b341f..2aeda5a2ad23f3 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/TransformChain.cs @@ -176,8 +176,13 @@ internal XmlElement GetXml(XmlDocument document, string ns) return transformsElement; } - internal void LoadXml(XmlElement value!!) + internal void LoadXml(XmlElement value) { + if (value is null) + { + throw new ArgumentNullException(nameof(value)); + } + XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs index a3b766792701b6..e5de6bee4c3c6f 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs @@ -31,15 +31,25 @@ private static bool HasNamespace(XmlElement element, string prefix, string value } // A helper function that determines if a namespace node is a committed attribute - internal static bool IsCommittedNamespace(XmlElement element!!, string prefix, string value) + internal static bool IsCommittedNamespace(XmlElement element, string prefix, string value) { + if (element is null) + { + throw new ArgumentNullException(nameof(element)); + } + string name = ((prefix.Length > 0) ? "xmlns:" + prefix : "xmlns"); if (element.HasAttribute(name) && element.GetAttribute(name) == value) return true; return false; } - internal static bool IsRedundantNamespace(XmlElement element!!, string prefix, string value) + internal static bool IsRedundantNamespace(XmlElement element, string prefix, string value) { + if (element is null) + { + throw new ArgumentNullException(nameof(element)); + } + XmlNode ancestorNode = ((XmlNode)element).ParentNode; while (ancestorNode != null) { @@ -190,8 +200,13 @@ internal static XmlReaderSettings GetSecureXmlReaderSettings(XmlResolver xmlReso return settings; } - internal static XmlDocument PreProcessDocumentInput(XmlDocument document!!, XmlResolver xmlResolver, string baseUri) + internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlResolver xmlResolver, string baseUri) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = document.PreserveWhitespace; @@ -209,8 +224,13 @@ internal static XmlDocument PreProcessDocumentInput(XmlDocument document!!, XmlR return doc; } - internal static XmlDocument PreProcessElementInput(XmlElement elem!!, XmlResolver xmlResolver, string baseUri) + internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri) { + if (elem is null) + { + throw new ArgumentNullException(nameof(elem)); + } + MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = true; // Normalize the document diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs index e7a4a6beab2cb5..513b1a82774e1e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs @@ -76,8 +76,13 @@ public override Type[] OutputTypes get { return _outputTypes; } } - public void AddExceptUri(string uri!!) + public void AddExceptUri(string uri) { + if (uri is null) + { + throw new ArgumentNullException(nameof(uri)); + } + ExceptUris.Add(uri); } @@ -155,8 +160,13 @@ private void LoadStreamInput(Stream stream) _encryptedDataList = document.SelectNodes("//enc:EncryptedData", _nsm); } - private void LoadXmlDocumentInput(XmlDocument document!!) + private void LoadXmlDocumentInput(XmlDocument document) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + _containingDocument = document; _nsm = new XmlNamespaceManager(document.NameTable); _nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs index 2fac6deb654884..429f925810d109 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigEnvelopedSignatureTransform.cs @@ -89,8 +89,13 @@ private void LoadStreamInput(Stream stream) _nsm.AddNamespace("dsig", SignedXml.XmlDsigNamespaceUrl); } - private void LoadXmlNodeListInput(XmlNodeList nodeList!!) + private void LoadXmlNodeListInput(XmlNodeList nodeList) { + if (nodeList is null) + { + throw new ArgumentNullException(nameof(nodeList)); + } + _containingDocument = Utils.GetOwnerDocument(nodeList); if (_containingDocument == null) throw new CryptographicException(SR.Cryptography_Xml_EnvelopedSignatureRequiresContext); @@ -100,8 +105,13 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList!!) _inputNodeList = nodeList; } - private void LoadXmlDocumentInput(XmlDocument doc!!) + private void LoadXmlDocumentInput(XmlDocument doc) { + if (doc is null) + { + throw new ArgumentNullException(nameof(doc)); + } + _containingDocument = doc; _nsm = new XmlNamespaceManager(_containingDocument.NameTable); _nsm.AddNamespace("dsig", SignedXml.XmlDsigNamespaceUrl); diff --git a/src/libraries/System.Security.Cryptography/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs b/src/libraries/System.Security.Cryptography/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs index aa79115fd978ab..0f40677892c354 100644 --- a/src/libraries/System.Security.Cryptography/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs +++ b/src/libraries/System.Security.Cryptography/src/Microsoft/Win32/SafeHandles/NCryptSafeHandles.cs @@ -72,9 +72,11 @@ protected SafeNCryptHandle() : base(true) } [SupportedOSPlatform("windows")] - protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle!!) + protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle) : base(true) { + ArgumentNullException.ThrowIfNull(parentHandle); + if (parentHandle.IsClosed || parentHandle.IsInvalid) throw new ArgumentException(SR.Argument_Invalid_SafeHandleInvalidOrClosed, nameof(parentHandle)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.cs index 98b49e12766d82..74d974f7cefe72 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.cs @@ -32,8 +32,13 @@ public AesCcm(byte[] key) ImportKey(key); } - public void Encrypt(byte[] nonce!!, byte[] plaintext!!, byte[] ciphertext!!, byte[] tag!!, byte[]? associatedData = null) + public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null) { + ArgumentNullException.ThrowIfNull(nonce); + ArgumentNullException.ThrowIfNull(plaintext); + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(tag); + Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -48,8 +53,13 @@ public void Encrypt( EncryptCore(nonce, plaintext, ciphertext, tag, associatedData); } - public void Decrypt(byte[] nonce!!, byte[] ciphertext!!, byte[] tag!!, byte[] plaintext!!, byte[]? associatedData = null) + public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null) { + ArgumentNullException.ThrowIfNull(nonce); + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(tag); + ArgumentNullException.ThrowIfNull(plaintext); + Decrypt((ReadOnlySpan)nonce, ciphertext, tag, plaintext, associatedData); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.cs index 3dca06a54f5124..02c7e6945eb907 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.cs @@ -33,8 +33,13 @@ public AesGcm(byte[] key) ImportKey(key); } - public void Encrypt(byte[] nonce!!, byte[] plaintext!!, byte[] ciphertext!!, byte[] tag!!, byte[]? associatedData = null) + public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null) { + ArgumentNullException.ThrowIfNull(nonce); + ArgumentNullException.ThrowIfNull(plaintext); + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(tag); + Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -49,8 +54,13 @@ public void Encrypt( EncryptCore(nonce, plaintext, ciphertext, tag, associatedData); } - public void Decrypt(byte[] nonce!!, byte[] ciphertext!!, byte[] tag!!, byte[] plaintext!!, byte[]? associatedData = null) + public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null) { + ArgumentNullException.ThrowIfNull(nonce); + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(tag); + ArgumentNullException.ThrowIfNull(plaintext); + Decrypt((ReadOnlySpan)nonce, ciphertext, tag, plaintext, associatedData); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesImplementation.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesImplementation.cs index 98c0bf9f4d6b04..6460995943515d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesImplementation.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesImplementation.cs @@ -178,8 +178,10 @@ protected override bool TryEncryptCfbCore( } } - private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting) + private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { + ArgumentNullException.ThrowIfNull(rgbKey); + // note: rbgIV is guaranteed to be cloned before this method, so no need to clone it again long keySize = rgbKey.Length * (long)BitsPerByte; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedData.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedData.cs index d914da039ad1f8..fcc93a066fe7ca 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedData.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedData.cs @@ -32,8 +32,10 @@ public AsnEncodedData(ReadOnlySpan rawData) Reset(null, rawData); } - public AsnEncodedData(AsnEncodedData asnEncodedData!!) + public AsnEncodedData(AsnEncodedData asnEncodedData) { + ArgumentNullException.ThrowIfNull(asnEncodedData); + Reset(asnEncodedData._oid, asnEncodedData._rawData); } @@ -99,8 +101,10 @@ public byte[] RawData } } - public virtual void CopyFrom(AsnEncodedData asnEncodedData!!) + public virtual void CopyFrom(AsnEncodedData asnEncodedData) { + ArgumentNullException.ThrowIfNull(asnEncodedData); + Reset(asnEncodedData._oid, asnEncodedData._rawData); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedDataCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedDataCollection.cs index 3a26812da74d83..df77d66d5f6570 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedDataCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnEncodedDataCollection.cs @@ -21,15 +21,19 @@ public AsnEncodedDataCollection(AsnEncodedData asnEncodedData) _list.Add(asnEncodedData); } - public int Add(AsnEncodedData asnEncodedData!!) + public int Add(AsnEncodedData asnEncodedData) { + ArgumentNullException.ThrowIfNull(asnEncodedData); + int indexOfNewItem = _list.Count; _list.Add(asnEncodedData); return indexOfNewItem; } - public void Remove(AsnEncodedData asnEncodedData!!) + public void Remove(AsnEncodedData asnEncodedData) { + ArgumentNullException.ThrowIfNull(asnEncodedData); + _list.Remove(asnEncodedData); } @@ -59,8 +63,10 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -75,8 +81,10 @@ void ICollection.CopyTo(Array array!!, int index) } } - public void CopyTo(AsnEncodedData[] array!!, int index) + public void CopyTo(AsnEncodedData[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + // Need to do part of the argument validation ourselves as AsnEncodedDataCollection throws // ArgumentOutOfRangeException where List<>.CopyTo() throws ArgumentException. diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs index a47c6d8dca0e94..68f6a244bcc217 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureDeformatter.cs @@ -12,8 +12,10 @@ protected AsymmetricSignatureDeformatter() { } public abstract void SetKey(AsymmetricAlgorithm key); public abstract void SetHashAlgorithm(string strName); - public virtual bool VerifySignature(HashAlgorithm hash!!, byte[] rgbSignature) + public virtual bool VerifySignature(HashAlgorithm hash, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(hash); + SetHashAlgorithm(hash.ToAlgorithmName()!); Debug.Assert(hash.Hash != null); return VerifySignature(hash.Hash, rgbSignature); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs index 1b3dbca3950153..c0f3bf892e0341 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsymmetricSignatureFormatter.cs @@ -12,8 +12,10 @@ protected AsymmetricSignatureFormatter() { } public abstract void SetKey(AsymmetricAlgorithm key); public abstract void SetHashAlgorithm(string strName); - public virtual byte[] CreateSignature(HashAlgorithm hash!!) + public virtual byte[] CreateSignature(HashAlgorithm hash) { + ArgumentNullException.ThrowIfNull(hash); + SetHashAlgorithm(hash.ToAlgorithmName()!); Debug.Assert(hash.Hash != null); return CreateSignature(hash.Hash); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Unix.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Unix.cs index 5b94f72103120f..7f23450c99174f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Unix.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Unix.cs @@ -18,8 +18,10 @@ internal static partial class CapiHelper private const string OID_SHA512 = "2.16.840.1.101.3.4.2.3"; // For backwards compat with CapiHelper.ObjToHashAlgorithm, use "hashAlg" as name - internal static HashAlgorithmName ObjToHashAlgorithmName(object hashAlg!!) + internal static HashAlgorithmName ObjToHashAlgorithmName(object hashAlg) { + ArgumentNullException.ThrowIfNull(hashAlg); + HashAlgorithmName? name = null; if (hashAlg is string) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs index 358cb2101828b0..efb181f8e6a298 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -1048,8 +1048,10 @@ public static int NameOrOidToHashAlgId(string? nameOrOid, OidGroup oidGroup) /// /// Helper for signing and verifications that accept a string/Type/HashAlgorithm to specify a hashing algorithm. /// - public static int ObjToHashAlgId(object hashAlg!!) + public static int ObjToHashAlgId(object hashAlg) { + ArgumentNullException.ThrowIfNull(hashAlg); + string? hashAlgString = hashAlg as string; if (hashAlgString != null) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.cs index 3ec803bcba92fe..63ac0a3f7eca2e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.cs @@ -27,8 +27,10 @@ public ChaCha20Poly1305(ReadOnlySpan key) ImportKey(key); } - public ChaCha20Poly1305(byte[] key!!) + public ChaCha20Poly1305(byte[] key) { + ArgumentNullException.ThrowIfNull(key); + ThrowIfNotSupported(); CheckKeySize(key.Length); @@ -43,8 +45,13 @@ private static void CheckKeySize(int keySizeInBytes) } } - public void Encrypt(byte[] nonce!!, byte[] plaintext!!, byte[] ciphertext!!, byte[] tag!!, byte[]? associatedData = null) + public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[]? associatedData = null) { + ArgumentNullException.ThrowIfNull(nonce); + ArgumentNullException.ThrowIfNull(plaintext); + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(tag); + Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -59,8 +66,13 @@ public void Encrypt( EncryptCore(nonce, plaintext, ciphertext, tag, associatedData); } - public void Decrypt(byte[] nonce!!, byte[] ciphertext!!, byte[] tag!!, byte[] plaintext!!, byte[]? associatedData = null) + public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[]? associatedData = null) { + ArgumentNullException.ThrowIfNull(nonce); + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(tag); + ArgumentNullException.ThrowIfNull(plaintext); + Decrypt((ReadOnlySpan)nonce, ciphertext, tag, plaintext, associatedData); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs index f60cd54f9ac1a1..550b4ce192c345 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Create.cs @@ -32,8 +32,10 @@ public static CngKey Create(CngAlgorithm algorithm, string? keyName) } [SupportedOSPlatform("windows")] - public static CngKey Create(CngAlgorithm algorithm!!, string? keyName, CngKeyCreationParameters? creationParameters) + public static CngKey Create(CngAlgorithm algorithm, string? keyName, CngKeyCreationParameters? creationParameters) { + ArgumentNullException.ThrowIfNull(algorithm); + if (creationParameters == null) creationParameters = new CngKeyCreationParameters(); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs index 34980a84e07385..d91f72af329e0b 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Exists.cs @@ -32,8 +32,11 @@ public static bool Exists(string keyName, CngProvider provider) } [SupportedOSPlatform("windows")] - public static bool Exists(string keyName!!, CngProvider provider!!, CngKeyOpenOptions options) + public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options) { + ArgumentNullException.ThrowIfNull(keyName); + ArgumentNullException.ThrowIfNull(provider); + using (SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider()) { SafeNCryptKeyHandle? keyHandle = null; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs index 5bb45c5dab5a5c..4c2a838682d387 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Export.cs @@ -18,8 +18,10 @@ public sealed partial class CngKey : IDisposable /// /// Export the key out of the KSP /// - public byte[] Export(CngKeyBlobFormat format!!) + public byte[] Export(CngKeyBlobFormat format) { + ArgumentNullException.ThrowIfNull(format); + int numBytesNeeded; ErrorCode errorCode = Interop.NCrypt.NCryptExportKey(_keyHandle, IntPtr.Zero, format.Format, IntPtr.Zero, null, 0, out numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Import.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Import.cs index 9a7cc942199c9d..25a2329d91879f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Import.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Import.cs @@ -102,20 +102,25 @@ ref MemoryMarshal.GetReference(keyBlob), } internal static CngKey Import( - byte[] keyBlob!!, + byte[] keyBlob, string? curveName, CngKeyBlobFormat format, CngProvider provider) { + ArgumentNullException.ThrowIfNull(keyBlob); + return Import(new ReadOnlySpan(keyBlob), curveName, format, provider); } internal static CngKey Import( ReadOnlySpan keyBlob, string? curveName, - CngKeyBlobFormat format!!, - CngProvider provider!!) + CngKeyBlobFormat format, + CngProvider provider) { + ArgumentNullException.ThrowIfNull(format); + ArgumentNullException.ThrowIfNull(provider); + SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider(); SafeNCryptKeyHandle? keyHandle; ErrorCode errorCode; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Open.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Open.cs index b2933879c8a5f1..c0b8b8ea91cea7 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Open.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Open.cs @@ -32,8 +32,11 @@ public static CngKey Open(string keyName, CngProvider provider) } [SupportedOSPlatform("windows")] - public static CngKey Open(string keyName!!, CngProvider provider!!, CngKeyOpenOptions openOptions) + public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { + ArgumentNullException.ThrowIfNull(keyName); + ArgumentNullException.ThrowIfNull(provider); + SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider(); SafeNCryptKeyHandle keyHandle; ErrorCode errorCode = Interop.NCrypt.NCryptOpenKey(providerHandle, out keyHandle, keyName, 0, openOptions); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs index 968e94627adc8b..46f440a605af5e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.OpenHandle.cs @@ -15,8 +15,10 @@ public sealed partial class CngKey : IDisposable /// Wrap an existing key handle with a CngKey object /// [SupportedOSPlatform("windows")] - public static CngKey Open(SafeNCryptKeyHandle keyHandle!!, CngKeyHandleOpenOptions keyHandleOpenOptions) + public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions) { + ArgumentNullException.ThrowIfNull(keyHandle); + if (keyHandle.IsClosed || keyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(keyHandle)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Properties.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Properties.cs index d20f7fe9522f2e..7c90ddc57d2885 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Properties.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngKey.Properties.cs @@ -15,8 +15,10 @@ public sealed partial class CngKey : IDisposable /// /// Get the value of an arbitrary property /// - public CngProperty GetProperty(string name!!, CngPropertyOptions options) + public CngProperty GetProperty(string name, CngPropertyOptions options) { + ArgumentNullException.ThrowIfNull(name); + byte[]? value = _keyHandle.GetProperty(name, options); if (value == null) throw ErrorCode.NTE_NOT_FOUND.ToCryptographicException(); @@ -30,8 +32,10 @@ public CngProperty GetProperty(string name!!, CngPropertyOptions options) /// /// Determine if a property exists on the key /// - public bool HasProperty(string name!!, CngPropertyOptions options) + public bool HasProperty(string name, CngPropertyOptions options) { + ArgumentNullException.ThrowIfNull(name); + unsafe { ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(_keyHandle, name, null, 0, out _, options); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngProperty.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngProperty.cs index 83f4dcf7dbe508..238a08dc4d18f3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngProperty.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngProperty.cs @@ -16,9 +16,11 @@ namespace System.Security.Cryptography [StructLayout(LayoutKind.Sequential)] // The [StructLayout] is here to prevent a spurious ApiReviewer alert. We do not actually depend on the layout of this struct. public struct CngProperty : IEquatable { - public CngProperty(string name!!, byte[]? value, CngPropertyOptions options) + public CngProperty(string name, byte[]? value, CngPropertyOptions options) : this() { + ArgumentNullException.ThrowIfNull(name); + Name = name; Options = options; _lazyHashCode = default(int?); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngSymmetricAlgorithmCore.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngSymmetricAlgorithmCore.cs index f13e177426eb11..a34db5cbbc3b80 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngSymmetricAlgorithmCore.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CngSymmetricAlgorithmCore.cs @@ -27,8 +27,11 @@ public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer) /// /// Constructs the core to use a stored CNG key. /// - public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName!!, CngProvider provider!!, CngKeyOpenOptions openOptions) + public CngSymmetricAlgorithmCore(ICngSymmetricAlgorithm outer, string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { + ArgumentNullException.ThrowIfNull(keyName); + ArgumentNullException.ThrowIfNull(provider); + _outer = outer; _keyName = keyName; @@ -168,8 +171,10 @@ private ILiteSymmetricCipher CreateLiteSymmetricCipher( encrypting); } - private UniversalCryptoTransform CreateCryptoTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting, PaddingMode padding, CipherMode mode, int feedbackSizeInBits) + private UniversalCryptoTransform CreateCryptoTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting, PaddingMode padding, CipherMode mode, int feedbackSizeInBits) { + ArgumentNullException.ThrowIfNull(rgbKey); + ValidateFeedbackSize(mode, feedbackSizeInBits); byte[] key = CopyAndValidateKey(rgbKey); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs index 1f05cf20b8331f..39b17d2af75168 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs @@ -333,8 +333,10 @@ public static void AddAlgorithm(Type algorithm, params string[] names) } [RequiresUnreferencedCode("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] - public static object? CreateFromName(string name!!, params object?[]? args) + public static object? CreateFromName(string name, params object?[]? args) { + ArgumentNullException.ThrowIfNull(name); + #if BROWSER switch (name) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs index 25678e56ac838a..00795d91213337 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs @@ -35,8 +35,10 @@ public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode { } - public CryptoStream(Stream stream, ICryptoTransform transform!!, CryptoStreamMode mode, bool leaveOpen) + public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, bool leaveOpen) { + ArgumentNullException.ThrowIfNull(transform); + _stream = stream; _transform = transform; _leaveOpen = leaveOpen; @@ -714,8 +716,10 @@ private async Task CopyToAsyncInternal(Stream destination, int bufferSize, Cance ArrayPool.Shared.Return(rentedBuffer); } - private void CheckCopyToArguments(Stream destination!!, int bufferSize) + private void CheckCopyToArguments(Stream destination, int bufferSize) { + ArgumentNullException.ThrowIfNull(destination); + EnsureNotDisposed(destination, nameof(destination)); if (!destination.CanWrite) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs index 8b1415ba8289f5..3f03f19418ead2 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DESCryptoServiceProvider.Windows.cs @@ -60,8 +60,10 @@ public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DES")] - private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting) + private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { + ArgumentNullException.ThrowIfNull(rgbKey); + // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again long keySize = rgbKey.Length * (long)BitsPerByte; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSA.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSA.cs index 802c0bdc7314be..815a7b5cc28294 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSA.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSA.cs @@ -91,8 +91,10 @@ protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgori protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => HashOneShotHelpers.HashData(hashAlgorithm, data); - public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm) + public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + // hashAlgorithm is verified in the overload return SignData(data, 0, data.Length, hashAlgorithm); @@ -119,8 +121,10 @@ public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm) /// /// An error occurred in the hashing or signing operation. /// - public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) + public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); + ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -128,8 +132,10 @@ public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, DSASignat return SignDataCore(data, hashAlgorithm, signatureFormat); } - public virtual byte[] SignData(byte[] data!!, int offset, int count, HashAlgorithmName hashAlgorithm) + public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) @@ -177,12 +183,14 @@ public virtual byte[] SignData(byte[] data!!, int offset, int count, HashAlgorit /// An error occurred in the hashing or signing operation. /// public byte[] SignData( - byte[] data!!, + byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); + if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) @@ -225,8 +233,9 @@ protected virtual byte[] SignDataCore( return AsymmetricAlgorithmHelpers.ConvertFromIeeeP1363Signature(sig, signatureFormat); } - public virtual byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm) + public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); byte[] hash = HashData(data, hashAlgorithm); @@ -254,8 +263,9 @@ public virtual byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm) /// /// An error occurred in the hashing or signing operation. /// - public byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) + public byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -281,8 +291,10 @@ protected virtual byte[] SignDataCore(Stream data, HashAlgorithmName hashAlgorit return CreateSignatureCore(hash, signatureFormat); } - public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm) + public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + return VerifyData(data, 0, data.Length, signature, hashAlgorithm); } @@ -358,8 +370,10 @@ public bool VerifyData( return VerifyDataCore(new ReadOnlySpan(data, offset, count), signature, hashAlgorithm, signatureFormat); } - public virtual bool VerifyData(Stream data!!, byte[] signature!!, HashAlgorithmName hashAlgorithm) + public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); byte[] hash = HashData(data, hashAlgorithm); @@ -383,8 +397,10 @@ public virtual bool VerifyData(Stream data!!, byte[] signature!!, HashAlgorithmN /// /// An error occurred in the signing operation. /// - public byte[] CreateSignature(byte[] rgbHash!!, DSASignatureFormat signatureFormat) + public byte[] CreateSignature(byte[] rgbHash, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -629,11 +645,13 @@ public virtual bool VerifyData( /// An error occurred in the hashing or verification operation. /// public bool VerifyData( - byte[] data!!, - byte[] signature!!, + byte[] data, + byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -664,11 +682,13 @@ public bool VerifyData( /// An error occurred in the hashing or verification operation. /// public bool VerifyData( - Stream data!!, - byte[] signature!!, + Stream data, + byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -771,8 +791,11 @@ protected virtual bool VerifyDataCore( /// /// An error occurred in the verification operation. /// - public bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!, DSASignatureFormat signatureFormat) + public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -886,10 +909,12 @@ private static Exception DerivedClassMustOverride() => public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -907,10 +932,12 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACng.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACng.cs index b158cd76619e06..6874e98f89abbc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACng.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACng.cs @@ -20,8 +20,10 @@ public sealed partial class DSACng : DSA /// if is not an DSA key /// if is null. [SupportedOSPlatform("windows")] - public DSACng(CngKey key!!) + public DSACng(CngKey key) { + ArgumentNullException.ThrowIfNull(key); + if (key.AlgorithmGroup != CngAlgorithmGroup.Dsa) throw new ArgumentException(SR.Cryptography_ArgDSARequiresDSAKey, nameof(key)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs index d5168360bd641c..41fff5154c8c7f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Unix.cs @@ -226,8 +226,10 @@ public override bool TrySignData(ReadOnlySpan data, Span destination } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "This is the implementation of DSACryptoServiceProvider")] - public byte[] SignHash(byte[] rgbHash!!, string str) + public byte[] SignHash(byte[] rgbHash, string str) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); if (rgbHash.Length != SHA1_HASHSIZE) @@ -243,8 +245,11 @@ public byte[] SignHash(byte[] rgbHash!!, string str) public bool VerifyData(byte[] rgbData, byte[] rgbSignature) => _impl.VerifyData(rgbData, rgbSignature, HashAlgorithmName.SHA1); - public bool VerifyHash(byte[] rgbHash!!, string str, byte[] rgbSignature!!) + public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + // For compat with Windows, no check for rgbHash.Length != SHA1_HASHSIZE // Only SHA1 allowed; the default value is SHA1 @@ -290,8 +295,10 @@ public override bool VerifySignature(ReadOnlySpan hash, ReadOnlySpan /// /// Find whether a DSS key blob is public. /// - private static bool IsPublic(byte[] keyBlob!!) + private static bool IsPublic(byte[] keyBlob) { + ArgumentNullException.ThrowIfNull(keyBlob); + // The CAPI DSS public key representation consists of the following sequence: // - BLOBHEADER (the first byte is bType) // - DSSPUBKEY or DSSPUBKEY_VER3 (the first field is the magic field) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs index 8b65b63b6c69d7..7d0e29060f3b93 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs @@ -478,8 +478,10 @@ protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) /// The hash value of the data to be signed. /// The name of the hash algorithm used to create the hash value of the data. /// The DSA signature for the specified hash value. - public byte[] SignHash(byte[] rgbHash!!, string? str) + public byte[] SignHash(byte[] rgbHash, string? str) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -504,8 +506,11 @@ public byte[] SignHash(byte[] rgbHash!!, string? str) /// The name of the hash algorithm used to create the hash value of the data. /// The signature data to be verified. /// true if the signature verifies as valid; otherwise, false. - public bool VerifyHash(byte[] rgbHash!!, string? str, byte[] rgbSignature!!) + public bool VerifyHash(byte[] rgbHash, string? str, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); return CapiHelper.VerifySign( @@ -520,8 +525,10 @@ public bool VerifyHash(byte[] rgbHash!!, string? str, byte[] rgbSignature!!) /// /// Find whether a DSS key blob is public. /// - private static bool IsPublic(byte[] keyBlob!!) + private static bool IsPublic(byte[] keyBlob) { + ArgumentNullException.ThrowIfNull(keyBlob); + // The CAPI DSS public key representation consists of the following sequence: // - BLOBHEADER (the first byte is bType) // - DSSPUBKEY or DSSPUBKEY_VER3 (the first field is the magic field) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSAOpenSsl.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSAOpenSsl.cs index add003a1273889..149da6ff43d9d6 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSAOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSAOpenSsl.cs @@ -36,8 +36,10 @@ public DSAOpenSsl(DSAParameters parameters) [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public DSAOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) + public DSAOpenSsl(SafeEvpPKeyHandle pkeyHandle) { + ArgumentNullException.ThrowIfNull(pkeyHandle); + if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureDeformatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureDeformatter.cs index 7843f4e7505918..dca40a481d5e11 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureDeformatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureDeformatter.cs @@ -9,13 +9,17 @@ public class DSASignatureDeformatter : AsymmetricSignatureDeformatter public DSASignatureDeformatter() { } - public DSASignatureDeformatter(AsymmetricAlgorithm key!!) : this() + public DSASignatureDeformatter(AsymmetricAlgorithm key) : this() { + ArgumentNullException.ThrowIfNull(key); + _dsaKey = (DSA)key; } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _dsaKey = (DSA)key; } @@ -28,8 +32,11 @@ public override void SetHashAlgorithm(string strName) } } - public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!) + public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + if (_dsaKey == null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_FormatterMissingKey); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureFormatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureFormatter.cs index 80575403ac50ff..0d9693ed49f65a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureFormatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSASignatureFormatter.cs @@ -9,13 +9,17 @@ public class DSASignatureFormatter : AsymmetricSignatureFormatter public DSASignatureFormatter() { } - public DSASignatureFormatter(AsymmetricAlgorithm key!!) : this() + public DSASignatureFormatter(AsymmetricAlgorithm key) : this() { + ArgumentNullException.ThrowIfNull(key); + _dsaKey = (DSA)key; } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _dsaKey = (DSA)key; } @@ -28,8 +32,10 @@ public override void SetHashAlgorithm(string strName) } } - public override byte[] CreateSignature(byte[] rgbHash!!) + public override byte[] CreateSignature(byte[] rgbHash) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (_dsaKey == null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_FormatterMissingKey); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DesImplementation.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DesImplementation.cs index dd73c5d6f57970..26937392486b83 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DesImplementation.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DesImplementation.cs @@ -47,8 +47,10 @@ public sealed override void GenerateKey() KeyValue = key; } - private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting) + private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { + ArgumentNullException.ThrowIfNull(rgbKey); + // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again long keySize = rgbKey.Length * (long)BitsPerByte; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECAlgorithm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECAlgorithm.cs index 3926fa6adbcaa2..df67054dfa79e7 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECAlgorithm.cs @@ -121,10 +121,12 @@ public virtual void GenerateKey(ECCurve curve) /// public override unsafe bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -191,10 +193,12 @@ public override unsafe bool TryExportEncryptedPkcs8PrivateKey( /// public override unsafe bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCurve.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCurve.cs index d5d17cdc2c1468..a4d1c454531688 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCurve.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCurve.cs @@ -102,8 +102,10 @@ public static ECCurve CreateFromOid(Oid curveOid) /// /// The Oid friendly name to use. /// An ECCurve representing a named curve. - public static ECCurve CreateFromFriendlyName(string oidFriendlyName!!) + public static ECCurve CreateFromFriendlyName(string oidFriendlyName) { + ArgumentNullException.ThrowIfNull(oidFriendlyName); + return ECCurve.CreateFromValueAndName(null, oidFriendlyName); } @@ -112,8 +114,10 @@ public static ECCurve CreateFromFriendlyName(string oidFriendlyName!!) /// /// The Oid value to use. /// An ECCurve representing a named curve. - public static ECCurve CreateFromValue(string oidValue!!) + public static ECCurve CreateFromValue(string oidValue) { + ArgumentNullException.ThrowIfNull(oidValue); + return ECCurve.CreateFromValueAndName(oidValue, null); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellman.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellman.cs index 7040290e496c87..a13617f05a2c9f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellman.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellman.cs @@ -32,8 +32,10 @@ public override string? SignatureAlgorithm public static partial ECDiffieHellman Create(ECParameters parameters); [RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)] - public static new ECDiffieHellman? Create(string algorithm!!) + public static new ECDiffieHellman? Create(string algorithm) { + ArgumentNullException.ThrowIfNull(algorithm); + return CryptoConfig.CreateFromName(algorithm) as ECDiffieHellman; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs index 84082e23bb507e..1e09a2a45578ed 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.Derive.cs @@ -8,8 +8,10 @@ namespace System.Security.Cryptography { public sealed partial class ECDiffieHellmanCng : ECDiffieHellman { - public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey!!) + public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) { + ArgumentNullException.ThrowIfNull(otherPartyPublicKey); + if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) { using (CngKey import = otherKey.Import()) @@ -37,8 +39,10 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl } } - public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey!!) + public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey) { + ArgumentNullException.ThrowIfNull(otherPartyPublicKey); + if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(otherPartyPublicKey)); if (otherPartyPublicKey.KeySize != KeySize) @@ -91,8 +95,10 @@ public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey!!) /// /// Get a handle to the secret agreement generated between two parties /// - public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicKey otherPartyPublicKey!!) + public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicKey otherPartyPublicKey) { + ArgumentNullException.ThrowIfNull(otherPartyPublicKey); + if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) { using (CngKey importedKey = otherKey.Import()) @@ -118,8 +124,10 @@ public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicK /// /// Get a handle to the secret agreement between two parties /// - public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey!!) + public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey) { + ArgumentNullException.ThrowIfNull(otherPartyPublicKey); + if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(otherPartyPublicKey)); if (otherPartyPublicKey.KeySize != KeySize) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs index 9e88e2c0db8dc1..56ae020b746fcc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCng.cs @@ -20,8 +20,10 @@ public sealed partial class ECDiffieHellmanCng : ECDiffieHellman private byte[]? _seed; [SupportedOSPlatform("windows")] - public ECDiffieHellmanCng(CngKey key!!) + public ECDiffieHellmanCng(CngKey key) { + ArgumentNullException.ThrowIfNull(key); + if (key.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(key)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs index f7911b66985e8a..4dc64ce6b1e2a3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanCngPublicKey.cs @@ -63,8 +63,11 @@ public CngKeyBlobFormat BlobFormat /// Hydrate a public key from a blob /// [SupportedOSPlatform("windows")] - public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob!!, CngKeyBlobFormat format!!) + public static ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, CngKeyBlobFormat format) { + ArgumentNullException.ThrowIfNull(publicKeyBlob); + ArgumentNullException.ThrowIfNull(format); + // Verify that the key can import successfully, because we did in the past. using (CngKey imported = CngKey.Import(publicKeyBlob, format)) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs index f3baa43a7a208c..47c7563d7aeb0b 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.cs @@ -22,8 +22,10 @@ public sealed partial class ECDiffieHellmanOpenSsl : ECDiffieHellman [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public ECDiffieHellmanOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) + public ECDiffieHellmanOpenSsl(SafeEvpPKeyHandle pkeyHandle) { + ArgumentNullException.ThrowIfNull(pkeyHandle); + if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs index 2dc74799cc2bd3..f7a27f60705199 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDiffieHellmanPublicKey.cs @@ -16,8 +16,10 @@ protected ECDiffieHellmanPublicKey() } [Obsolete(Obsoletions.EcDhPublicKeyBlobMessage, DiagnosticId = Obsoletions.EcDhPublicKeyBlobDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] - protected ECDiffieHellmanPublicKey(byte[] keyBlob!!) + protected ECDiffieHellmanPublicKey(byte[] keyBlob) { + ArgumentNullException.ThrowIfNull(keyBlob); + _keyBlob = (byte[])keyBlob.Clone(); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsa.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsa.cs index e590ec853c6fa4..3ce8e02a2afd2d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsa.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsa.cs @@ -30,20 +30,25 @@ protected ECDsa() { } public static partial ECDsa Create(ECParameters parameters); [RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)] - public static new ECDsa? Create(string algorithm!!) + public static new ECDsa? Create(string algorithm) { + ArgumentNullException.ThrowIfNull(algorithm); + return CryptoConfig.CreateFromName(algorithm) as ECDsa; } - public virtual byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm) + public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + // hashAlgorithm is verified in the overload return SignData(data, 0, data.Length, hashAlgorithm); } - public virtual byte[] SignData(byte[] data!!, int offset, int count, HashAlgorithmName hashAlgorithm) + public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) @@ -91,12 +96,13 @@ public virtual byte[] SignData(byte[] data!!, int offset, int count, HashAlgorit /// An error occurred in the hashing or signing operation. /// public byte[] SignData( - byte[] data!!, + byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) @@ -185,8 +191,9 @@ protected virtual byte[] SignDataCore( /// /// An error occurred in the hashing or signing operation. /// - public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) + public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -215,8 +222,9 @@ public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, DSASignat /// /// An error occurred in the hashing or signing operation. /// - public byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) + public byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -262,8 +270,10 @@ protected virtual byte[] SignDataCore( /// /// An error occurred in the signing operation. /// - public byte[] SignHash(byte[] hash!!, DSASignatureFormat signatureFormat) + public byte[] SignHash(byte[] hash, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(hash); + if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -406,16 +416,19 @@ protected virtual bool TrySignDataCore( return TrySignHashCore(hash, destination, signatureFormat, out bytesWritten); } - public virtual byte[] SignData(Stream data!!, HashAlgorithmName hashAlgorithm) + public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash); } - public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm) + public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + return VerifyData(data, 0, data.Length, signature, hashAlgorithm); } @@ -517,8 +530,10 @@ public bool VerifyData( /// /// An error occurred in the hashing or verification operation. /// - public bool VerifyData(byte[] data!!, byte[] signature!!, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) + public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -600,8 +615,10 @@ protected virtual bool VerifyDataCore( return VerifyHashCore(hashSpan, signature, signatureFormat); } - public bool VerifyData(Stream data!!, byte[] signature!!, HashAlgorithmName hashAlgorithm) + public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(signature); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); byte[] hash = HashData(data, hashAlgorithm); @@ -631,11 +648,14 @@ public bool VerifyData(Stream data!!, byte[] signature!!, HashAlgorithmName hash /// An error occurred in the hashing or verification operation. /// public bool VerifyData( - Stream data!!, - byte[] signature!!, + Stream data, + byte[] signature, HashAlgorithmName hashAlgorithm, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(signature); + ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -810,8 +830,11 @@ public virtual bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signa /// /// An error occurred in the verification operation. /// - public bool VerifyHash(byte[] hash!!, byte[] signature!!, DSASignatureFormat signatureFormat) + public bool VerifyHash(byte[] hash, byte[] signature, DSASignatureFormat signatureFormat) { + ArgumentNullException.ThrowIfNull(hash); + ArgumentNullException.ThrowIfNull(signature); + if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaCng.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaCng.cs index 934f0106b05c42..ad50b1b33896c8 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaCng.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaCng.cs @@ -38,8 +38,10 @@ public CngAlgorithm HashAlgorithm /// if is not an ECDsa key /// if is null. [SupportedOSPlatform("windows")] - public ECDsaCng(CngKey key!!) + public ECDsaCng(CngKey key) { + ArgumentNullException.ThrowIfNull(key); + if (!IsEccAlgorithmGroup(key.AlgorithmGroup)) throw new ArgumentException(SR.Cryptography_ArgECDsaRequiresECDsaKey, nameof(key)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaOpenSsl.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaOpenSsl.cs index e45bb748e8232c..b3060fe828e586 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECDsaOpenSsl.cs @@ -22,8 +22,10 @@ public sealed partial class ECDsaOpenSsl : ECDsa [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public ECDsaOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) + public ECDsaOpenSsl(SafeEvpPKeyHandle pkeyHandle) { + ArgumentNullException.ThrowIfNull(pkeyHandle); + if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs index 6d3b9bf593c054..d42556b38e3278 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HKDF.cs @@ -25,8 +25,10 @@ public static class HKDF /// The input keying material. /// The optional salt value (a non-secret random value). If not provided it defaults to a byte array of zeros. /// The pseudo random key (prk). - public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm!!, byte[]? salt = null) + public static byte[] Extract(HashAlgorithmName hashAlgorithmName, byte[] ikm, byte[]? salt = null) { + ArgumentNullException.ThrowIfNull(ikm); + int hashLength = HashLength(hashAlgorithmName); byte[] prk = new byte[hashLength]; @@ -79,8 +81,10 @@ private static void Extract(HashAlgorithmName hashAlgorithmName, int hashLength, /// The output keying material. /// is . /// is less than 1. - public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk!!, int outputLength, byte[]? info = null) + public static byte[] Expand(HashAlgorithmName hashAlgorithmName, byte[] prk, int outputLength, byte[]? info = null) { + ArgumentNullException.ThrowIfNull(prk); + if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); @@ -202,8 +206,10 @@ private static void Expand(HashAlgorithmName hashAlgorithmName, int hashLength, /// The output keying material. /// is . /// is less than 1. - public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm!!, int outputLength, byte[]? salt = null, byte[]? info = null) + public static byte[] DeriveKey(HashAlgorithmName hashAlgorithmName, byte[] ikm, int outputLength, byte[]? salt = null, byte[]? info = null) { + ArgumentNullException.ThrowIfNull(ikm); + if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs index 4c0a6d4e9c543e..a30aa44fb53873 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs @@ -33,8 +33,10 @@ public HMACMD5() { } - public HMACMD5(byte[] key!!) + public HMACMD5(byte[] key) { + ArgumentNullException.ThrowIfNull(key); + this.HashName = HashAlgorithmNames.MD5; _hMacCommon = new HMACCommon(HashAlgorithmNames.MD5, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -82,8 +84,11 @@ protected override bool TryHashFinal(Span destination, out int bytesWritte /// /// or is . /// - public static byte[] HashData(byte[] key!!, byte[] source!!) + public static byte[] HashData(byte[] key, byte[] source) { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -171,8 +176,10 @@ public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source /// does not support reading. ///

/// - public static int HashData(ReadOnlySpan key, Stream source!!, Span destination) + public static int HashData(ReadOnlySpan key, Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -194,8 +201,10 @@ public static int HashData(ReadOnlySpan key, Stream source!!, Span d /// /// does not support reading. /// - public static byte[] HashData(ReadOnlySpan key, Stream source!!) + public static byte[] HashData(ReadOnlySpan key, Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -214,8 +223,10 @@ public static byte[] HashData(ReadOnlySpan key, Stream source!!) /// /// does not support reading. /// - public static byte[] HashData(byte[] key!!, Stream source) + public static byte[] HashData(byte[] key, Stream source) { + ArgumentNullException.ThrowIfNull(key); + return HashData(new ReadOnlySpan(key), source); } @@ -235,8 +246,10 @@ public static byte[] HashData(byte[] key!!, Stream source) /// /// does not support reading. /// - public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -259,8 +272,10 @@ public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream s /// /// does not support reading. /// - public static ValueTask HashDataAsync(byte[] key!!, Stream source, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(byte[] key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(key); + return HashDataAsync(new ReadOnlyMemory(key), source, cancellationToken); } @@ -290,10 +305,12 @@ public static ValueTask HashDataAsync(byte[] key!!, Stream source, Cance /// public static ValueTask HashDataAsync( ReadOnlyMemory key, - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs index 6f8d583b3e33ea..80f9a95fb47958 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs @@ -34,8 +34,10 @@ public HMACSHA1() { } - public HMACSHA1(byte[] key!!) + public HMACSHA1(byte[] key) { + ArgumentNullException.ThrowIfNull(key); + this.HashName = HashAlgorithmNames.SHA1; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA1, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -90,8 +92,11 @@ protected override bool TryHashFinal(Span destination, out int bytesWritte /// /// or is . /// - public static byte[] HashData(byte[] key!!, byte[] source!!) + public static byte[] HashData(byte[] key, byte[] source) { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -179,8 +184,10 @@ public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source /// does not support reading. ///

/// - public static int HashData(ReadOnlySpan key, Stream source!!, Span destination) + public static int HashData(ReadOnlySpan key, Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -202,8 +209,10 @@ public static int HashData(ReadOnlySpan key, Stream source!!, Span d /// /// does not support reading. /// - public static byte[] HashData(ReadOnlySpan key, Stream source!!) + public static byte[] HashData(ReadOnlySpan key, Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -222,8 +231,10 @@ public static byte[] HashData(ReadOnlySpan key, Stream source!!) /// /// does not support reading. /// - public static byte[] HashData(byte[] key!!, Stream source) + public static byte[] HashData(byte[] key, Stream source) { + ArgumentNullException.ThrowIfNull(key); + return HashData(new ReadOnlySpan(key), source); } @@ -243,8 +254,10 @@ public static byte[] HashData(byte[] key!!, Stream source) /// /// does not support reading. /// - public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -267,8 +280,10 @@ public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream s /// /// does not support reading. /// - public static ValueTask HashDataAsync(byte[] key!!, Stream source, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(byte[] key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(key); + return HashDataAsync(new ReadOnlyMemory(key), source, cancellationToken); } @@ -298,10 +313,12 @@ public static ValueTask HashDataAsync(byte[] key!!, Stream source, Cance /// public static ValueTask HashDataAsync( ReadOnlyMemory key, - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs index a2c21d0a70cab1..0e1348eefba1e3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs @@ -33,8 +33,10 @@ public HMACSHA256() { } - public HMACSHA256(byte[] key!!) + public HMACSHA256(byte[] key) { + ArgumentNullException.ThrowIfNull(key); + this.HashName = HashAlgorithmNames.SHA256; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA256, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -82,8 +84,11 @@ protected override bool TryHashFinal(Span destination, out int bytesWritte /// /// or is . /// - public static byte[] HashData(byte[] key!!, byte[] source!!) + public static byte[] HashData(byte[] key, byte[] source) { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -171,8 +176,10 @@ public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source /// does not support reading. ///

/// - public static int HashData(ReadOnlySpan key, Stream source!!, Span destination) + public static int HashData(ReadOnlySpan key, Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -194,8 +201,10 @@ public static int HashData(ReadOnlySpan key, Stream source!!, Span d /// /// does not support reading. /// - public static byte[] HashData(ReadOnlySpan key, Stream source!!) + public static byte[] HashData(ReadOnlySpan key, Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -214,8 +223,10 @@ public static byte[] HashData(ReadOnlySpan key, Stream source!!) /// /// does not support reading. /// - public static byte[] HashData(byte[] key!!, Stream source) + public static byte[] HashData(byte[] key, Stream source) { + ArgumentNullException.ThrowIfNull(key); + return HashData(new ReadOnlySpan(key), source); } @@ -235,8 +246,10 @@ public static byte[] HashData(byte[] key!!, Stream source) /// /// does not support reading. /// - public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -259,8 +272,10 @@ public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream s /// /// does not support reading. /// - public static ValueTask HashDataAsync(byte[] key!!, Stream source, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(byte[] key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(key); + return HashDataAsync(new ReadOnlyMemory(key), source, cancellationToken); } @@ -290,10 +305,12 @@ public static ValueTask HashDataAsync(byte[] key!!, Stream source, Cance /// public static ValueTask HashDataAsync( ReadOnlyMemory key, - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs index 970bf891f8f5b1..e7b54ee4868dbb 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs @@ -33,8 +33,10 @@ public HMACSHA384() { } - public HMACSHA384(byte[] key!!) + public HMACSHA384(byte[] key) { + ArgumentNullException.ThrowIfNull(key); + this.HashName = HashAlgorithmNames.SHA384; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA384, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -99,8 +101,11 @@ protected override bool TryHashFinal(Span destination, out int bytesWritte /// /// or is . /// - public static byte[] HashData(byte[] key!!, byte[] source!!) + public static byte[] HashData(byte[] key, byte[] source) { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -188,8 +193,10 @@ public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source /// does not support reading. ///

/// - public static int HashData(ReadOnlySpan key, Stream source!!, Span destination) + public static int HashData(ReadOnlySpan key, Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -211,8 +218,10 @@ public static int HashData(ReadOnlySpan key, Stream source!!, Span d /// /// does not support reading. /// - public static byte[] HashData(ReadOnlySpan key, Stream source!!) + public static byte[] HashData(ReadOnlySpan key, Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -231,8 +240,10 @@ public static byte[] HashData(ReadOnlySpan key, Stream source!!) /// /// does not support reading. /// - public static byte[] HashData(byte[] key!!, Stream source) + public static byte[] HashData(byte[] key, Stream source) { + ArgumentNullException.ThrowIfNull(key); + return HashData(new ReadOnlySpan(key), source); } @@ -252,8 +263,10 @@ public static byte[] HashData(byte[] key!!, Stream source) /// /// does not support reading. /// - public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -276,8 +289,10 @@ public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream s /// /// does not support reading. /// - public static ValueTask HashDataAsync(byte[] key!!, Stream source, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(byte[] key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(key); + return HashDataAsync(new ReadOnlyMemory(key), source, cancellationToken); } @@ -307,10 +322,12 @@ public static ValueTask HashDataAsync(byte[] key!!, Stream source, Cance /// public static ValueTask HashDataAsync( ReadOnlyMemory key, - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs index a1c3393064728e..e280573f94fece 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs @@ -33,8 +33,10 @@ public HMACSHA512() { } - public HMACSHA512(byte[] key!!) + public HMACSHA512(byte[] key) { + ArgumentNullException.ThrowIfNull(key); + this.HashName = HashAlgorithmNames.SHA512; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA512, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -96,8 +98,11 @@ protected override bool TryHashFinal(Span destination, out int bytesWritte /// /// or is . /// - public static byte[] HashData(byte[] key!!, byte[] source!!) + public static byte[] HashData(byte[] key, byte[] source) { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -185,8 +190,10 @@ public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source /// does not support reading. ///

/// - public static int HashData(ReadOnlySpan key, Stream source!!, Span destination) + public static int HashData(ReadOnlySpan key, Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -208,8 +215,10 @@ public static int HashData(ReadOnlySpan key, Stream source!!, Span d /// /// does not support reading. /// - public static byte[] HashData(ReadOnlySpan key, Stream source!!) + public static byte[] HashData(ReadOnlySpan key, Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -228,8 +237,10 @@ public static byte[] HashData(ReadOnlySpan key, Stream source!!) /// /// does not support reading. /// - public static byte[] HashData(byte[] key!!, Stream source) + public static byte[] HashData(byte[] key, Stream source) { + ArgumentNullException.ThrowIfNull(key); + return HashData(new ReadOnlySpan(key), source); } @@ -249,8 +260,10 @@ public static byte[] HashData(byte[] key!!, Stream source) /// /// does not support reading. /// - public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -273,8 +286,10 @@ public static ValueTask HashDataAsync(ReadOnlyMemory key, Stream s /// /// does not support reading. /// - public static ValueTask HashDataAsync(byte[] key!!, Stream source, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(byte[] key, Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(key); + return HashDataAsync(new ReadOnlyMemory(key), source, cancellationToken); } @@ -304,10 +319,12 @@ public static ValueTask HashDataAsync(byte[] key!!, Stream source, Cance /// public static ValueTask HashDataAsync( ReadOnlyMemory key, - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs index b816674e858516..27ee6410f6e6ac 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithm.cs @@ -77,8 +77,10 @@ public bool TryComputeHash(ReadOnlySpan source, Span destination, ou return true; } - public byte[] ComputeHash(byte[] buffer!!, int offset, int count) + public byte[] ComputeHash(byte[] buffer, int offset, int count) { + ArgumentNullException.ThrowIfNull(buffer); + if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > buffer.Length)) @@ -120,9 +122,11 @@ public byte[] ComputeHash(Stream inputStream) } public Task ComputeHashAsync( - Stream inputStream!!, + Stream inputStream, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(inputStream); + if (_disposed) throw new ObjectDisposedException(null); @@ -235,8 +239,10 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input return outputBytes; } - private void ValidateTransformBlock(byte[] inputBuffer!!, int inputOffset, int inputCount) + private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount) { + ArgumentNullException.ThrowIfNull(inputBuffer); + if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum); if (inputCount < 0 || inputCount > inputBuffer.Length) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithmName.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithmName.cs index ae5ac7ae45d8f2..f7df0f24280251 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithmName.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashAlgorithmName.cs @@ -121,8 +121,10 @@ public override int GetHashCode() /// /// is null. /// - public static bool TryFromOid(string oidValue!!, out HashAlgorithmName value) + public static bool TryFromOid(string oidValue, out HashAlgorithmName value) { + ArgumentNullException.ThrowIfNull(oidValue); + switch (oidValue) { case Oids.Md5: diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs index 0ec19fe155b704..281634063f2918 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HashProvider.cs @@ -12,8 +12,10 @@ namespace System.Security.Cryptography internal abstract class HashProvider : IDisposable { // Adds new data to be hashed. This can be called repeatedly in order to hash data from noncontiguous sources. - public void AppendHashData(byte[] data!!, int offset, int count) + public void AppendHashData(byte[] data, int offset, int count) { + ArgumentNullException.ThrowIfNull(data); + // AppendHashData can be called via exposed APIs (e.g. a type that derives from // HMACSHA1 and calls HashCore) and could be passed bad data from there. It could // also receive a bad count from HashAlgorithm reading from a Stream that returns diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs index b33c4d7477377a..8ee41347893ba0 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/IncrementalHash.cs @@ -56,8 +56,10 @@ private IncrementalHash(HashAlgorithmName name, HMACCommon hmac) /// The data to process. /// is null. /// The object has already been disposed. - public void AppendData(byte[] data!!) + public void AppendData(byte[] data) { + ArgumentNullException.ThrowIfNull(data); + AppendData(new ReadOnlySpan(data)); } @@ -81,8 +83,10 @@ public void AppendData(byte[] data!!) /// . - . /// /// The object has already been disposed. - public void AppendData(byte[] data!!, int offset, int count) + public void AppendData(byte[] data, int offset, int count) { + ArgumentNullException.ThrowIfNull(data); + if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > data.Length)) @@ -342,8 +346,10 @@ public static IncrementalHash CreateHash(HashAlgorithmName hashAlgorithm) /// /// is not a known hash algorithm. [UnsupportedOSPlatform("browser")] - public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key!!) + public static IncrementalHash CreateHMAC(HashAlgorithmName hashAlgorithm, byte[] key) { + ArgumentNullException.ThrowIfNull(key); + return CreateHMAC(hashAlgorithm, (ReadOnlySpan)key); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs index edbb9b610f1b3f..6fa8eec0780e46 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs @@ -48,8 +48,10 @@ protected MD5() /// /// is . /// - public static byte[] HashData(byte[] source!!) + public static byte[] HashData(byte[] source) { + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(source)); } @@ -131,8 +133,10 @@ public static bool TryHashData(ReadOnlySpan source, Span destination /// does not support reading. ///

/// - public static int HashData(Stream source!!, Span destination) + public static int HashData(Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -153,8 +157,10 @@ public static int HashData(Stream source!!, Span destination) /// /// does not support reading. /// - public static byte[] HashData(Stream source!!) + public static byte[] HashData(Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -176,8 +182,10 @@ public static byte[] HashData(Stream source!!) /// /// does not support reading. /// - public static ValueTask HashDataAsync(Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -208,10 +216,12 @@ public static ValueTask HashDataAsync(Stream source!!, CancellationToken ///

/// public static ValueTask HashDataAsync( - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs index 3ec5be3a97f6a8..e53b628de39503 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Oid.cs @@ -32,16 +32,20 @@ public Oid(string? value, string? friendlyName) _hasInitializedFriendlyName = friendlyName != null; } - public Oid(Oid oid!!) + public Oid(Oid oid) { + ArgumentNullException.ThrowIfNull(oid); + _value = oid._value; _friendlyName = oid._friendlyName; _group = oid._group; _hasInitializedFriendlyName = oid._hasInitializedFriendlyName; } - public static Oid FromFriendlyName(string friendlyName!!, OidGroup group) + public static Oid FromFriendlyName(string friendlyName, OidGroup group) { + ArgumentNullException.ThrowIfNull(friendlyName); + string? oidValue = OidLookup.ToOid(friendlyName, group, fallBackToAllGroups: false); if (oidValue == null) throw new CryptographicException(SR.Cryptography_Oid_InvalidName); @@ -49,8 +53,10 @@ public static Oid FromFriendlyName(string friendlyName!!, OidGroup group) return new Oid(oidValue, friendlyName, group); } - public static Oid FromOidValue(string oidValue!!, OidGroup group) + public static Oid FromOidValue(string oidValue, OidGroup group) { + ArgumentNullException.ThrowIfNull(oidValue); + string? friendlyName = OidLookup.ToFriendlyName(oidValue, group, fallBackToAllGroups: false); if (friendlyName == null) throw new CryptographicException(SR.Cryptography_Oid_InvalidValue); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs index 4817a86e47b1e8..25ced97b3d6aea 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidCollection.cs @@ -66,8 +66,10 @@ public Oid? this[string oid] IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -82,8 +84,10 @@ void ICollection.CopyTo(Array array!!, int index) } } - public void CopyTo(Oid[] array!!, int index) + public void CopyTo(Oid[] array, int index) { + ArgumentNullException.ThrowIfNull(array); + // Need to do part of the argument validation ourselves as OidCollection throws // ArgumentOutOfRangeException where List<>.CopyTo() throws ArgumentException. if (index < 0 || index >= array.Length) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidLookup.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidLookup.cs index 17031b902e7c59..80134ead051d4d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidLookup.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/OidLookup.cs @@ -18,8 +18,10 @@ internal static partial class OidLookup // // Attempts to map a friendly name to an OID. Returns null if not a known name. // - public static string? ToFriendlyName(string oid!!, OidGroup oidGroup, bool fallBackToAllGroups) + public static string? ToFriendlyName(string oid, OidGroup oidGroup, bool fallBackToAllGroups) { + ArgumentNullException.ThrowIfNull(oid); + string? mappedName; bool shouldUseCache = ShouldUseCache(oidGroup); @@ -54,8 +56,10 @@ internal static partial class OidLookup // // Attempts to retrieve the friendly name for an OID. Returns null if not a known or valid OID. // - public static string? ToOid(string friendlyName!!, OidGroup oidGroup, bool fallBackToAllGroups) + public static string? ToOid(string friendlyName, OidGroup oidGroup, bool fallBackToAllGroups) { + ArgumentNullException.ThrowIfNull(friendlyName); + if (friendlyName.Length == 0) return null; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs index 597b47f4a14f8a..139b32009df876 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs @@ -54,8 +54,10 @@ public sealed override void GenerateKey() Key = RandomNumberGenerator.GetBytes(KeySize / BitsPerByte); } - private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting) + private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { + ArgumentNullException.ThrowIfNull(rgbKey); + // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again if (!ValidKeySize(rgbKey.Length)) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs index beac03aad08e50..6f88edd5a6594f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSA.cs @@ -162,8 +162,10 @@ public virtual byte[] DecryptValue(byte[] rgb) => public virtual byte[] EncryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop - public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { + ArgumentNullException.ThrowIfNull(data); + return SignData(data, 0, data.Length, hashAlgorithm, padding); } @@ -211,8 +213,10 @@ public virtual bool TrySignData(ReadOnlySpan data, Span destination, return false; } - public bool VerifyData(byte[] data!!, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { + ArgumentNullException.ThrowIfNull(data); + return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } @@ -375,10 +379,12 @@ private unsafe AsnWriter WritePkcs8PrivateKey() public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -396,10 +402,12 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters!!, + PbeParameters pbeParameters, Span destination, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(pbeParameters); + PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACng.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACng.cs index f51f993a3c45d3..105ccbca38f792 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACng.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACng.cs @@ -20,8 +20,10 @@ public sealed partial class RSACng : RSA /// if is not an RSA key /// if is null. [SupportedOSPlatform("windows")] - public RSACng(CngKey key!!) + public RSACng(CngKey key) { + ArgumentNullException.ThrowIfNull(key); + if (key.AlgorithmGroup != CngAlgorithmGroup.Rsa) throw new ArgumentException(SR.Cryptography_ArgRSARequiresRSAKey, nameof(key)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs index 1f598cdbd8312c..374faf2d85d376 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Unix.cs @@ -40,8 +40,10 @@ public RSACryptoServiceProvider(CspParameters parameters) => public CspKeyContainerInfo CspKeyContainerInfo => throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspKeyContainerInfo))); - public byte[] Decrypt(byte[] rgb!!, bool fOAEP) + public byte[] Decrypt(byte[] rgb, bool fOAEP) { + ArgumentNullException.ThrowIfNull(rgb); + // size check -- must be exactly the modulus size if (rgb.Length != (KeySize / 8)) throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); @@ -49,16 +51,21 @@ public byte[] Decrypt(byte[] rgb!!, bool fOAEP) return _impl.Decrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1); } - public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) + public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(padding); + return padding == RSAEncryptionPadding.Pkcs1 ? Decrypt(data, fOAEP: false) : padding == RSAEncryptionPadding.OaepSHA1 ? Decrypt(data, fOAEP: true) : // For compat, this prevents OaepSHA2 options as fOAEP==true will cause Decrypt to use OaepSHA1 throw PaddingModeNotSupported(); } - public override bool TryDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding!!, out int bytesWritten) + public override bool TryDecrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(padding); + if (data.Length != (KeySize / 8)) throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) @@ -76,21 +83,28 @@ protected override void Dispose(bool disposing) } } - public byte[] Encrypt(byte[] rgb!!, bool fOAEP) + public byte[] Encrypt(byte[] rgb, bool fOAEP) { + ArgumentNullException.ThrowIfNull(rgb); + return _impl.Encrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1); } - public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) + public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(padding); + return padding == RSAEncryptionPadding.Pkcs1 ? Encrypt(data, fOAEP: false) : padding == RSAEncryptionPadding.OaepSHA1 ? Encrypt(data, fOAEP: true) : // For compat, this prevents OaepSHA2 options as fOAEP==true will cause Decrypt to use OaepSHA1 throw PaddingModeNotSupported(); } - public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding!!, out int bytesWritten) + public override bool TryEncrypt(ReadOnlySpan data, Span destination, RSAEncryptionPadding padding, out int bytesWritten) { + ArgumentNullException.ThrowIfNull(padding); + if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) throw PaddingModeNotSupported(); @@ -161,17 +175,41 @@ public override int KeySize public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; - public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.SignData(data, hashAlgorithm, padding); + public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + ArgumentNullException.ThrowIfNull(padding); - public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.SignData(data, offset, count, hashAlgorithm, padding); + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.SignData(data, hashAlgorithm, padding); + } + + public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + ArgumentNullException.ThrowIfNull(padding); - public override bool TrySignData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!, out int bytesWritten) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.TrySignData(data, destination, hashAlgorithm, padding, out bytesWritten); + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.SignData(data, offset, count, hashAlgorithm, padding); + } + + public override bool TrySignData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) + { + ArgumentNullException.ThrowIfNull(padding); + + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.TrySignData(data, destination, hashAlgorithm, padding, out bytesWritten); + } public byte[] SignData(byte[] buffer, int offset, int count, object halg) => _impl.SignData(buffer, offset, count, CapiHelper.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); @@ -182,16 +220,34 @@ public byte[] SignData(byte[] buffer, object halg) => public byte[] SignData(Stream inputStream, object halg) => _impl.SignData(inputStream, CapiHelper.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); - public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.SignHash(hash, hashAlgorithm, padding); + public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + ArgumentNullException.ThrowIfNull(padding); + + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.SignHash(hash, hashAlgorithm, padding); + } - public override bool TrySignHash(ReadOnlySpan hash, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!, out int bytesWritten) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.TrySignHash(hash, destination, hashAlgorithm, padding, out bytesWritten); + public override bool TrySignHash(ReadOnlySpan hash, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) + { + ArgumentNullException.ThrowIfNull(padding); - public byte[] SignHash(byte[] rgbHash!!, string str) + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.TrySignHash(hash, destination, hashAlgorithm, padding, out bytesWritten); + } + + public byte[] SignHash(byte[] rgbHash, string str) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -204,25 +260,55 @@ public byte[] SignHash(byte[] rgbHash!!, string str) public bool VerifyData(byte[] buffer, object halg, byte[] signature) => _impl.VerifyData(buffer, signature, CapiHelper.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1); - public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding); + public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + ArgumentNullException.ThrowIfNull(padding); + + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } - public override bool VerifyData(ReadOnlySpan data, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.VerifyData(data, signature, hashAlgorithm, padding); + return _impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding); + } - public override bool VerifyHash(byte[] hash!!, byte[] signature!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + public override bool VerifyData(ReadOnlySpan data, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { + ArgumentNullException.ThrowIfNull(padding); + + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.VerifyData(data, signature, hashAlgorithm, padding); + } + + public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + ArgumentNullException.ThrowIfNull(hash); + ArgumentNullException.ThrowIfNull(signature); + return VerifyHash((ReadOnlySpan)hash, (ReadOnlySpan)signature, hashAlgorithm, padding); } - public override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => - padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : - _impl.VerifyHash(hash, signature, hashAlgorithm, padding); + public override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + { + ArgumentNullException.ThrowIfNull(padding); + + if (padding != RSASignaturePadding.Pkcs1) + { + throw PaddingModeNotSupported(); + } + + return _impl.VerifyHash(hash, signature, hashAlgorithm, padding); + } - public bool VerifyHash(byte[] rgbHash!!, string str, byte[] rgbSignature!!) + public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + return VerifyHash( (ReadOnlySpan)rgbHash, (ReadOnlySpan)rgbSignature, CapiHelper.NameOrOidToHashAlgorithmName(str), RSASignaturePadding.Pkcs1); @@ -239,8 +325,10 @@ private static Exception PaddingModeNotSupported() /// /// find whether an RSA key blob is public. /// - private static bool IsPublic(byte[] keyBlob!!) + private static bool IsPublic(byte[] keyBlob) { + ArgumentNullException.ThrowIfNull(keyBlob); + // The CAPI RSA public key representation consists of the following sequence: // - BLOBHEADER // - RSAPUBKEY diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs index 3bf4aede41c624..2b9eef4bad5664 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs @@ -261,8 +261,10 @@ public static bool UseMachineKeyStore /// encrypted data /// true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding /// decrypted data - public byte[] Decrypt(byte[] rgb!!, bool fOAEP) + public byte[] Decrypt(byte[] rgb, bool fOAEP) { + ArgumentNullException.ThrowIfNull(rgb); + // Save the KeySize value to a local because it has non-trivial cost. int keySize = KeySize; @@ -314,8 +316,10 @@ protected override void Dispose(bool disposing) /// raw data to encrypt /// true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding /// Encrypted key - public byte[] Encrypt(byte[] rgb!!, bool fOAEP) + public byte[] Encrypt(byte[] rgb, bool fOAEP) { + ArgumentNullException.ThrowIfNull(rgb); + if (fOAEP) { int rsaSize = (KeySize + 7) / 8; @@ -474,8 +478,10 @@ public byte[] SignData(Stream inputStream, object halg) /// The input data for which to compute the hash /// The hash algorithm to use to create the hash value. /// The RSA signature for the specified data. - public byte[] SignHash(byte[] rgbHash!!, string? str) + public byte[] SignHash(byte[] rgbHash, string? str) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -518,8 +524,11 @@ public bool VerifyData(byte[] buffer, object halg, byte[] signature) /// /// Verifies the signature of a hash value. /// - public bool VerifyHash(byte[] rgbHash!!, string str, byte[] rgbSignature!!) + public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); return VerifyHash(rgbHash, calgHash, rgbSignature); } @@ -541,8 +550,10 @@ private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature) /// /// find whether an RSA key blob is public. /// - private static bool IsPublic(byte[] keyBlob!!) + private static bool IsPublic(byte[] keyBlob) { + ArgumentNullException.ThrowIfNull(keyBlob); + // The CAPI RSA public key representation consists of the following sequence: // - BLOBHEADER // - RSAPUBKEY @@ -570,8 +581,11 @@ private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm) => _ => throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name), }; - public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) + public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(padding); + if (padding == RSAEncryptionPadding.Pkcs1) { return Encrypt(data, fOAEP: false); @@ -586,8 +600,11 @@ public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) } } - public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) + public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(padding); + if (padding == RSAEncryptionPadding.Pkcs1) { return Decrypt(data, fOAEP: false); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs index 4895e87d05ae83..7f71223c154a64 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeDeformatter.cs @@ -8,8 +8,10 @@ public class RSAOAEPKeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter private RSA? _rsaKey; public RSAOAEPKeyExchangeDeformatter() { } - public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key!!) + public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } @@ -27,8 +29,10 @@ public override byte[] DecryptKeyExchange(byte[] rgbData) return _rsaKey.Decrypt(rgbData, RSAEncryptionPadding.OaepSHA1); } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs index 2026b7766ae80d..ac1f3052841b7c 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOAEPKeyExchangeFormatter.cs @@ -10,8 +10,10 @@ public class RSAOAEPKeyExchangeFormatter : AsymmetricKeyExchangeFormatter private RandomNumberGenerator? RngValue; public RSAOAEPKeyExchangeFormatter() { } - public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key!!) + public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } @@ -50,8 +52,10 @@ public RandomNumberGenerator? Rng set { RngValue = value; } } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOpenSsl.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOpenSsl.cs index 30891570cf0459..b2ad115fd34d9d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOpenSsl.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAOpenSsl.cs @@ -65,8 +65,10 @@ public RSAOpenSsl(IntPtr handle) [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public RSAOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) + public RSAOpenSsl(SafeEvpPKeyHandle pkeyHandle) { + ArgumentNullException.ThrowIfNull(pkeyHandle); + if (pkeyHandle.IsInvalid) throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs index f01cdf3cbcb85d..5b61a33f1af71d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeDeformatter.cs @@ -12,8 +12,10 @@ public class RSAPKCS1KeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter public RSAPKCS1KeyExchangeDeformatter() { } - public RSAPKCS1KeyExchangeDeformatter(AsymmetricAlgorithm key!!) + public RSAPKCS1KeyExchangeDeformatter(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } @@ -37,8 +39,10 @@ public override byte[] DecryptKeyExchange(byte[] rgbIn) return _rsaKey.Decrypt(rgbIn, RSAEncryptionPadding.Pkcs1); } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs index 58b439942a24cc..15e06ef48c2b6d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1KeyExchangeFormatter.cs @@ -12,8 +12,10 @@ public class RSAPKCS1KeyExchangeFormatter : AsymmetricKeyExchangeFormatter public RSAPKCS1KeyExchangeFormatter() { } - public RSAPKCS1KeyExchangeFormatter(AsymmetricAlgorithm key!!) + public RSAPKCS1KeyExchangeFormatter(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } @@ -31,8 +33,10 @@ public RandomNumberGenerator? Rng set { RngValue = value; } } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs index b3376f9b8ddc19..11ce2d106648e5 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureDeformatter.cs @@ -13,13 +13,17 @@ public class RSAPKCS1SignatureDeformatter : AsymmetricSignatureDeformatter private string? _algName; public RSAPKCS1SignatureDeformatter() { } - public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key!!) + public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } @@ -38,8 +42,11 @@ public override void SetHashAlgorithm(string strName) } } - public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!) + public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { + ArgumentNullException.ThrowIfNull(rgbHash); + ArgumentNullException.ThrowIfNull(rgbSignature); + if (_algName == null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_FormatterMissingAlgorithm); if (_rsaKey == null) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs index af101c039ab964..a85e5d68f6fea9 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSAPKCS1SignatureFormatter.cs @@ -14,13 +14,17 @@ public class RSAPKCS1SignatureFormatter : AsymmetricSignatureFormatter public RSAPKCS1SignatureFormatter() { } - public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key!!) + public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } - public override void SetKey(AsymmetricAlgorithm key!!) + public override void SetKey(AsymmetricAlgorithm key) { + ArgumentNullException.ThrowIfNull(key); + _rsaKey = (RSA)key; } @@ -39,8 +43,10 @@ public override void SetHashAlgorithm(string strName) } } - public override byte[] CreateSignature(byte[] rgbHash!!) + public override byte[] CreateSignature(byte[] rgbHash) { + ArgumentNullException.ThrowIfNull(rgbHash); + if (_algName == null) throw new CryptographicUnexpectedOperationException(SR.Cryptography_FormatterMissingAlgorithm); if (_rsaKey == null) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs index 88b0afdf970a25..43a8d019fc0470 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs @@ -163,8 +163,10 @@ public static byte[] GetBytes(int count) return ret; } - internal static void VerifyGetBytes(byte[] data!!, int offset, int count) + internal static void VerifyGetBytes(byte[] data, int offset, int count) { + ArgumentNullException.ThrowIfNull(data); + if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGeneratorImplementation.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGeneratorImplementation.cs index 2bc9b39aa4dfcf..0a35f3572fcb40 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGeneratorImplementation.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGeneratorImplementation.cs @@ -26,8 +26,10 @@ internal static unsafe void FillSpan(Span data) } } - public override void GetBytes(byte[] data!!) + public override void GetBytes(byte[] data) { + ArgumentNullException.ThrowIfNull(data); + GetBytes(new Span(data)); } @@ -45,8 +47,10 @@ public override unsafe void GetBytes(Span data) } } - public override void GetNonZeroBytes(byte[] data!!) + public override void GetNonZeroBytes(byte[] data) { + ArgumentNullException.ThrowIfNull(data); + GetNonZeroBytes(new Span(data)); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs index e5251f5c8b9bb2..9b8f8a9b6af369 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.OneShot.cs @@ -38,12 +38,15 @@ public partial class Rfc2898DeriveBytes /// , and . /// public static byte[] Pbkdf2( - byte[] password!!, - byte[] salt!!, + byte[] password, + byte[] salt, int iterations, HashAlgorithmName hashAlgorithm, int outputLength) { + ArgumentNullException.ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(salt); + return Pbkdf2(new ReadOnlySpan(password), new ReadOnlySpan(salt), iterations, hashAlgorithm, outputLength); } @@ -157,12 +160,15 @@ public static void Pbkdf2( /// and use . /// public static byte[] Pbkdf2( - string password!!, - byte[] salt!!, + string password, + byte[] salt, int iterations, HashAlgorithmName hashAlgorithm, int outputLength) { + ArgumentNullException.ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(salt); + return Pbkdf2(password.AsSpan(), new ReadOnlySpan(salt), iterations, hashAlgorithm, outputLength); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs index ac6d379c274a1b..f3aba550e5ccdf 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Rfc2898DeriveBytes.cs @@ -91,8 +91,10 @@ public Rfc2898DeriveBytes(string password, int saltSize, int iterations, HashAlg Initialize(); } - internal Rfc2898DeriveBytes(byte[] password, byte[] salt!!, int iterations, HashAlgorithmName hashAlgorithm, bool clearPassword) + internal Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, HashAlgorithmName hashAlgorithm, bool clearPassword) { + ArgumentNullException.ThrowIfNull(salt); + if (iterations <= 0) throw new ArgumentOutOfRangeException(nameof(iterations), SR.ArgumentOutOfRange_NeedPosNum); if (password is null) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs index d8623e523c2873..f65c7c5286f1b3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs @@ -47,8 +47,10 @@ protected SHA1() /// /// is . /// - public static byte[] HashData(byte[] source!!) + public static byte[] HashData(byte[] source) { + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(source)); } @@ -130,8 +132,10 @@ public static bool TryHashData(ReadOnlySpan source, Span destination /// does not support reading. ///

/// - public static int HashData(Stream source!!, Span destination) + public static int HashData(Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -152,8 +156,10 @@ public static int HashData(Stream source!!, Span destination) /// /// does not support reading. /// - public static byte[] HashData(Stream source!!) + public static byte[] HashData(Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -175,8 +181,10 @@ public static byte[] HashData(Stream source!!) /// /// does not support reading. /// - public static ValueTask HashDataAsync(Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -207,10 +215,12 @@ public static ValueTask HashDataAsync(Stream source!!, CancellationToken ///

/// public static ValueTask HashDataAsync( - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs index fd8a03ca96fbf5..ce7480e973c526 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs @@ -46,8 +46,10 @@ protected SHA256() /// /// is . /// - public static byte[] HashData(byte[] source!!) + public static byte[] HashData(byte[] source) { + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(source)); } @@ -130,8 +132,10 @@ public static bool TryHashData(ReadOnlySpan source, Span destination /// does not support reading. ///

/// - public static int HashData(Stream source!!, Span destination) + public static int HashData(Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -152,8 +156,10 @@ public static int HashData(Stream source!!, Span destination) /// /// does not support reading. /// - public static byte[] HashData(Stream source!!) + public static byte[] HashData(Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -175,8 +181,10 @@ public static byte[] HashData(Stream source!!) /// /// does not support reading. /// - public static ValueTask HashDataAsync(Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -207,10 +215,12 @@ public static ValueTask HashDataAsync(Stream source!!, CancellationToken ///

/// public static ValueTask HashDataAsync( - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs index fa8618d50118d8..36156528fa097f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs @@ -46,8 +46,10 @@ protected SHA384() /// /// is . /// - public static byte[] HashData(byte[] source!!) + public static byte[] HashData(byte[] source) { + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(source)); } @@ -129,8 +131,10 @@ public static bool TryHashData(ReadOnlySpan source, Span destination /// does not support reading. ///

/// - public static int HashData(Stream source!!, Span destination) + public static int HashData(Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -151,8 +155,10 @@ public static int HashData(Stream source!!, Span destination) /// /// does not support reading. /// - public static byte[] HashData(Stream source!!) + public static byte[] HashData(Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -174,8 +180,10 @@ public static byte[] HashData(Stream source!!) /// /// does not support reading. /// - public static ValueTask HashDataAsync(Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -206,10 +214,12 @@ public static ValueTask HashDataAsync(Stream source!!, CancellationToken ///

/// public static ValueTask HashDataAsync( - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs index 6833478ca89e0b..5e275b03de7ed5 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs @@ -46,8 +46,10 @@ protected SHA512() /// /// is . /// - public static byte[] HashData(byte[] source!!) + public static byte[] HashData(byte[] source) { + ArgumentNullException.ThrowIfNull(source); + return HashData(new ReadOnlySpan(source)); } @@ -129,8 +131,10 @@ public static bool TryHashData(ReadOnlySpan source, Span destination /// does not support reading. ///

/// - public static int HashData(Stream source!!, Span destination) + public static int HashData(Stream source, Span destination) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); @@ -151,8 +155,10 @@ public static int HashData(Stream source!!, Span destination) /// /// does not support reading. /// - public static byte[] HashData(Stream source!!) + public static byte[] HashData(Stream source) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -174,8 +180,10 @@ public static byte[] HashData(Stream source!!) /// /// does not support reading. /// - public static ValueTask HashDataAsync(Stream source!!, CancellationToken cancellationToken = default) + public static ValueTask HashDataAsync(Stream source, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (!source.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable, nameof(source)); @@ -206,10 +214,12 @@ public static ValueTask HashDataAsync(Stream source!!, CancellationToken ///

/// public static ValueTask HashDataAsync( - Stream source!!, + Stream source, Memory destination, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(source); + if (destination.Length < HashSizeInBytes) throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SignatureDescription.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SignatureDescription.cs index e50b658422a630..64c038c71f3bee 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SignatureDescription.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SignatureDescription.cs @@ -16,8 +16,10 @@ public SignatureDescription() { } - public SignatureDescription(SecurityElement el!!) + public SignatureDescription(SecurityElement el) { + ArgumentNullException.ThrowIfNull(el); + KeyAlgorithm = el.SearchForTextOfTag("Key"); DigestAlgorithm = el.SearchForTextOfTag("Digest"); FormatterAlgorithm = el.SearchForTextOfTag("Formatter"); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs index fffae90dbbac62..8f7df3e9e0eb05 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SymmetricAlgorithm.cs @@ -445,8 +445,10 @@ public int GetCiphertextLengthCfb(int plaintextLength, PaddingMode paddingMode = /// /// This method's behavior is defined by . /// - public byte[] DecryptEcb(byte[] ciphertext!!, PaddingMode paddingMode) + public byte[] DecryptEcb(byte[] ciphertext, PaddingMode paddingMode) { + ArgumentNullException.ThrowIfNull(ciphertext); + // Padding mode is validated by callee. return DecryptEcb(new ReadOnlySpan(ciphertext), paddingMode); } @@ -561,8 +563,10 @@ public bool TryDecryptEcb(ReadOnlySpan ciphertext, Span destination, /// /// This method's behavior is defined by . /// - public byte[] EncryptEcb(byte[] plaintext!!, PaddingMode paddingMode) + public byte[] EncryptEcb(byte[] plaintext, PaddingMode paddingMode) { + ArgumentNullException.ThrowIfNull(plaintext); + // paddingMode is validated by callee return EncryptEcb(new ReadOnlySpan(plaintext), paddingMode); } @@ -682,8 +686,11 @@ public bool TryEncryptEcb(ReadOnlySpan plaintext, Span destination, /// /// This method's behavior is defined by . /// - public byte[] DecryptCbc(byte[] ciphertext!!, byte[] iv!!, PaddingMode paddingMode = PaddingMode.PKCS7) + public byte[] DecryptCbc(byte[] ciphertext, byte[] iv, PaddingMode paddingMode = PaddingMode.PKCS7) { + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(iv); + return DecryptCbc(new ReadOnlySpan(ciphertext), new ReadOnlySpan(iv), paddingMode); } @@ -834,8 +841,11 @@ public bool TryDecryptCbc( /// /// This method's behavior is defined by . /// - public byte[] EncryptCbc(byte[] plaintext!!, byte[] iv!!, PaddingMode paddingMode = PaddingMode.PKCS7) + public byte[] EncryptCbc(byte[] plaintext, byte[] iv, PaddingMode paddingMode = PaddingMode.PKCS7) { + ArgumentNullException.ThrowIfNull(plaintext); + ArgumentNullException.ThrowIfNull(iv); + return EncryptCbc(new ReadOnlySpan(plaintext), new ReadOnlySpan(iv), paddingMode); } @@ -1003,8 +1013,11 @@ public bool TryEncryptCbc( /// /// This method's behavior is defined by . /// - public byte[] DecryptCfb(byte[] ciphertext!!, byte[] iv!!, PaddingMode paddingMode = PaddingMode.None, int feedbackSizeInBits = 8) + public byte[] DecryptCfb(byte[] ciphertext, byte[] iv, PaddingMode paddingMode = PaddingMode.None, int feedbackSizeInBits = 8) { + ArgumentNullException.ThrowIfNull(ciphertext); + ArgumentNullException.ThrowIfNull(iv); + return DecryptCfb( new ReadOnlySpan(ciphertext), new ReadOnlySpan(iv), diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/TripleDesImplementation.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/TripleDesImplementation.cs index 8add56937be4ba..b63e4f69bac9aa 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/TripleDesImplementation.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/TripleDesImplementation.cs @@ -47,8 +47,10 @@ public sealed override void GenerateKey() Key = RandomNumberGenerator.GetBytes(KeySize / BitsPerByte); } - private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting) + private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) { + ArgumentNullException.ThrowIfNull(rgbKey); + // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again long keySize = rgbKey.Length * (long)BitsPerByte; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs index 7a357ff6bc8815..0bf92d61b029d6 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoTransform.cs @@ -68,8 +68,7 @@ public void Dispose() public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { - if (inputBuffer == null) - throw new ArgumentNullException(nameof(inputBuffer)); + ArgumentNullException.ThrowIfNull(inputBuffer); if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset)); if (inputOffset > inputBuffer.Length) @@ -80,8 +79,8 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b throw new ArgumentOutOfRangeException(nameof(inputCount), SR.Cryptography_MustTransformWholeBlock); if (inputCount > inputBuffer.Length - inputOffset) throw new ArgumentOutOfRangeException(nameof(inputCount), SR.Argument_InvalidOffLen); - if (outputBuffer == null) - throw new ArgumentNullException(nameof(outputBuffer)); + + ArgumentNullException.ThrowIfNull(outputBuffer); if (outputOffset > outputBuffer.Length) throw new ArgumentOutOfRangeException(nameof(outputOffset)); if (inputCount > outputBuffer.Length - outputOffset) @@ -92,8 +91,10 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b return numBytesWritten; } - public byte[] TransformFinalBlock(byte[] inputBuffer!!, int inputOffset, int inputCount) + public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { + ArgumentNullException.ThrowIfNull(inputBuffer); + if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset)); if (inputCount < 0) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateExtensionsCommon.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateExtensionsCommon.cs index ceaba8195a80c0..c6d0b78119c35c 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateExtensionsCommon.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateExtensionsCommon.cs @@ -8,10 +8,12 @@ namespace System.Security.Cryptography.X509Certificates internal static class CertificateExtensionsCommon { public static T? GetPublicKey( - this X509Certificate2 certificate!!, + this X509Certificate2 certificate, Predicate? matchesConstraints = null) where T : AsymmetricAlgorithm { + ArgumentNullException.ThrowIfNull(certificate); + string oidValue = GetExpectedOidValue(); PublicKey publicKey = certificate.PublicKey; Oid algorithmOid = publicKey.Oid; @@ -42,10 +44,12 @@ internal static class CertificateExtensionsCommon } public static T? GetPrivateKey( - this X509Certificate2 certificate!!, + this X509Certificate2 certificate, Predicate? matchesConstraints = null) where T : AsymmetricAlgorithm { + ArgumentNullException.ThrowIfNull(certificate); + string oidValue = GetExpectedOidValue(); if (!certificate.HasPrivateKey || oidValue != certificate.PublicKey.Oid.Value) return null; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs index 27003867981b00..ca3c1ac642511d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs @@ -58,8 +58,10 @@ public sealed class CertificateRequest /// The hash algorithm to use when signing the certificate or certificate request. /// /// - public CertificateRequest(string subjectName!!, ECDsa key!!, HashAlgorithmName hashAlgorithm) + public CertificateRequest(string subjectName, ECDsa key, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(subjectName); + ArgumentNullException.ThrowIfNull(key); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); SubjectName = new X500DistinguishedName(subjectName); @@ -83,8 +85,10 @@ public CertificateRequest(string subjectName!!, ECDsa key!!, HashAlgorithmName h /// /// The hash algorithm to use when signing the certificate or certificate request. /// - public CertificateRequest(X500DistinguishedName subjectName!!, ECDsa key!!, HashAlgorithmName hashAlgorithm) + public CertificateRequest(X500DistinguishedName subjectName, ECDsa key, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(subjectName); + ArgumentNullException.ThrowIfNull(key); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); SubjectName = subjectName; @@ -176,8 +180,10 @@ public CertificateRequest( /// /// The hash algorithm to use when signing the certificate or certificate request. /// - public CertificateRequest(X500DistinguishedName subjectName!!, PublicKey publicKey!!, HashAlgorithmName hashAlgorithm) + public CertificateRequest(X500DistinguishedName subjectName, PublicKey publicKey, HashAlgorithmName hashAlgorithm) { + ArgumentNullException.ThrowIfNull(subjectName); + ArgumentNullException.ThrowIfNull(publicKey); ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm)); SubjectName = subjectName; @@ -238,8 +244,10 @@ public byte[] CreateSigningRequest() /// /// A with which to sign the request. /// - public byte[] CreateSigningRequest(X509SignatureGenerator signatureGenerator!!) + public byte[] CreateSigningRequest(X509SignatureGenerator signatureGenerator) { + ArgumentNullException.ThrowIfNull(signatureGenerator); + X501Attribute[] attributes = Array.Empty(); if (CertificateExtensions.Count > 0) @@ -405,11 +413,13 @@ public X509Certificate2 Create( /// which does not accept a value. /// public X509Certificate2 Create( - X509Certificate2 issuerCertificate!!, + X509Certificate2 issuerCertificate, DateTimeOffset notBefore, DateTimeOffset notAfter, ReadOnlySpan serialNumber) { + ArgumentNullException.ThrowIfNull(issuerCertificate); + if (!issuerCertificate.HasPrivateKey) throw new ArgumentException(SR.Cryptography_CertReq_IssuerRequiresPrivateKey, nameof(issuerCertificate)); if (notAfter < notBefore) @@ -581,12 +591,15 @@ public X509Certificate2 Create( /// has length 0. /// Any error occurs during the signing operation. public X509Certificate2 Create( - X500DistinguishedName issuerName!!, - X509SignatureGenerator generator!!, + X500DistinguishedName issuerName, + X509SignatureGenerator generator, DateTimeOffset notBefore, DateTimeOffset notAfter, ReadOnlySpan serialNumber) { + ArgumentNullException.ThrowIfNull(issuerName); + ArgumentNullException.ThrowIfNull(generator); + if (notAfter < notBefore) throw new ArgumentException(SR.Cryptography_CertReq_DatesReversed); if (serialNumber == null || serialNumber.Length < 1) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs index 53006b879413bd..e2214b0de89440 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Windows.cs @@ -19,7 +19,9 @@ private ChainPal(SafeX509ChainHandle chain) internal static partial IChainPal FromHandle(IntPtr chainContext) { if (chainContext == IntPtr.Zero) + { throw new ArgumentNullException(nameof(chainContext)); + } SafeX509ChainHandle certChainHandle = Interop.Crypt32.CertDuplicateCertificateChain(chainContext); if (certChainHandle == null || certChainHandle.IsInvalid) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/DSACertificateExtensions.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/DSACertificateExtensions.cs index 62c0ca791c00ee..b19422ecd9f778 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/DSACertificateExtensions.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/DSACertificateExtensions.cs @@ -30,8 +30,11 @@ public static class DSACertificateExtensions return certificate.GetPrivateKey(); } - public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate!!, DSA privateKey!!) + public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate, DSA privateKey) { + ArgumentNullException.ThrowIfNull(certificate); + ArgumentNullException.ThrowIfNull(privateKey); + if (certificate.HasPrivateKey) throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ECDsaCertificateExtensions.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ECDsaCertificateExtensions.cs index f41048bf494c91..de72605e294214 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ECDsaCertificateExtensions.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ECDsaCertificateExtensions.cs @@ -27,8 +27,11 @@ public static class ECDsaCertificateExtensions return certificate.GetPrivateKey(cert => HasECDsaKeyUsage(cert)); } - public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate!!, ECDsa privateKey!!) + public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate, ECDsa privateKey) { + ArgumentNullException.ThrowIfNull(certificate); + ArgumentNullException.ThrowIfNull(privateKey); + if (certificate.HasPrivateKey) throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs index 15ec8ad9cae654..5995fdf19464ae 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.cs @@ -214,8 +214,10 @@ private static X509KeyUsageFlags ConfirmedX509KeyUsage(object findValue) // Enforce that no dot starts or ends the Oid, and disallow double dots. // Enforce there is at least one dot separator. // - internal static void ValidateOidValue(string keyValue!!) + internal static void ValidateOidValue(string keyValue) { + ArgumentNullException.ThrowIfNull(keyValue); + int len = keyValue.Length; if (len < 2) throw new ArgumentException(SR.Argument_InvalidOidValue); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs10CertificationRequestInfo.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs10CertificationRequestInfo.cs index 3d2667c7c335e9..24b7ee5dfafb21 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs10CertificationRequestInfo.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs10CertificationRequestInfo.cs @@ -18,10 +18,13 @@ internal sealed class Pkcs10CertificationRequestInfo internal Collection Attributes { get; } = new Collection(); internal Pkcs10CertificationRequestInfo( - X500DistinguishedName subject!!, - PublicKey publicKey!!, + X500DistinguishedName subject, + PublicKey publicKey, IEnumerable attributes) { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(publicKey); + Subject = subject; PublicKey = publicKey; diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs9ExtensionRequest.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs9ExtensionRequest.cs index 7ecc5f499c31a0..63ffc96f34662b 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs9ExtensionRequest.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Pkcs9ExtensionRequest.cs @@ -14,8 +14,10 @@ internal Pkcs9ExtensionRequest(IEnumerable extensions) { } - private static byte[] EncodeAttribute(IEnumerable extensions!!) + private static byte[] EncodeAttribute(IEnumerable extensions) { + ArgumentNullException.ThrowIfNull(extensions); + AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); using (writer.PushSequence()) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/RSACertificateExtensions.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/RSACertificateExtensions.cs index 1aa566f2020d6e..332400cd100fa3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/RSACertificateExtensions.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/RSACertificateExtensions.cs @@ -27,8 +27,11 @@ public static class RSACertificateExtensions return certificate.GetPrivateKey(); } - public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate!!, RSA privateKey!!) + public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate, RSA privateKey) { + ArgumentNullException.ThrowIfNull(certificate); + ArgumentNullException.ThrowIfNull(privateKey); + if (certificate.HasPrivateKey) throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs index f2e6494481f620..f7c6079585c63e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Windows.cs @@ -15,7 +15,9 @@ internal sealed partial class StorePal : IDisposable, IStorePal, IExportPal, ILo internal static partial IStorePal FromHandle(IntPtr storeHandle) { if (storeHandle == IntPtr.Zero) + { throw new ArgumentNullException(nameof(storeHandle)); + } SafeCertStoreHandle certStoreHandle = Interop.Crypt32.CertDuplicateStore(storeHandle); if (certStoreHandle == null || certStoreHandle.IsInvalid) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.macOS.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.macOS.cs index cfd418b27a545f..5587d6330e5cdc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.macOS.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.macOS.cs @@ -14,7 +14,9 @@ internal sealed partial class StorePal internal static partial IStorePal FromHandle(IntPtr storeHandle) { if (storeHandle == IntPtr.Zero) + { throw new ArgumentNullException(nameof(storeHandle)); + } var keychainHandle = new SafeKeychainHandle(storeHandle); Interop.CoreFoundation.CFRetain(storeHandle); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/SubjectAlternativeNameBuilder.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/SubjectAlternativeNameBuilder.cs index eb1e69c34ceedc..0d34c6d472a40c 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/SubjectAlternativeNameBuilder.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/SubjectAlternativeNameBuilder.cs @@ -33,13 +33,17 @@ public void AddDnsName(string dnsName) AddGeneralName(new GeneralNameAsn { DnsName = s_idnMapping.GetAscii(dnsName) }); } - public void AddUri(Uri uri!!) + public void AddUri(Uri uri) { + ArgumentNullException.ThrowIfNull(uri); + AddGeneralName(new GeneralNameAsn { Uri = uri.AbsoluteUri.ToString() }); } - public void AddIpAddress(IPAddress ipAddress!!) + public void AddIpAddress(IPAddress ipAddress) { + ArgumentNullException.ThrowIfNull(ipAddress); + AddGeneralName(new GeneralNameAsn { IPAddress = ipAddress.GetAddressBytes() }); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs index 8ea61a2bcc00f9..1da4b68c8fa372 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedName.cs @@ -69,8 +69,10 @@ public override string Format(bool multiLine) return X509Pal.Instance.X500DistinguishedNameFormat(RawData, multiLine); } - private static byte[] Encode(string distinguishedName!!, X500DistinguishedNameFlags flags) + private static byte[] Encode(string distinguishedName, X500DistinguishedNameFlags flags) { + ArgumentNullException.ThrowIfNull(distinguishedName); + ThrowIfInvalid(flags); return X509Pal.Instance.X500DistinguishedNameEncode(distinguishedName, flags); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs index f46596ab29884e..9c434efab49138 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs @@ -59,8 +59,9 @@ public sealed class X500DistinguishedNameBuilder /// is not encodable as defined by . /// /// - public void Add(string oidValue, string value!!, UniversalTagNumber? stringEncodingType = null) + public void Add(string oidValue, string value, UniversalTagNumber? stringEncodingType = null) { + ArgumentNullException.ThrowIfNull(value); ArgumentException.ThrowIfNullOrEmpty(oidValue); UniversalTagNumber tag = GetAndValidateTagNumber(stringEncodingType); @@ -92,8 +93,11 @@ public void Add(string oidValue, string value!!, UniversalTagNumber? stringEncod /// is not encodable as defined by . /// /// - public void Add(Oid oid!!, string value!!, UniversalTagNumber? stringEncodingType = null) + public void Add(Oid oid, string value, UniversalTagNumber? stringEncodingType = null) { + ArgumentNullException.ThrowIfNull(oid); + ArgumentNullException.ThrowIfNull(value); + if (string.IsNullOrEmpty(oid.Value)) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid)); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs index 23ad47853233f4..92e1e5b2ff34d0 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs @@ -156,8 +156,10 @@ public X509Certificate(string fileName, SecureString? password) } [UnsupportedOSPlatform("browser")] - public X509Certificate(string fileName!!, string? password, X509KeyStorageFlags keyStorageFlags) + public X509Certificate(string fileName, string? password, X509KeyStorageFlags keyStorageFlags) { + ArgumentNullException.ThrowIfNull(fileName); + ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -166,8 +168,10 @@ public X509Certificate(string fileName!!, string? password, X509KeyStorageFlags } } - private protected X509Certificate(string fileName!!, ReadOnlySpan password, X509KeyStorageFlags keyStorageFlags) + private protected X509Certificate(string fileName, ReadOnlySpan password, X509KeyStorageFlags keyStorageFlags) { + ArgumentNullException.ThrowIfNull(fileName); + ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -179,9 +183,11 @@ private protected X509Certificate(string fileName!!, ReadOnlySpan password [UnsupportedOSPlatform("browser")] [CLSCompliantAttribute(false)] #pragma warning disable SYSLIB0026 - public X509Certificate(string fileName!!, SecureString? password, X509KeyStorageFlags keyStorageFlags) : this() + public X509Certificate(string fileName, SecureString? password, X509KeyStorageFlags keyStorageFlags) : this() #pragma warning restore SYSLIB0026 { + ArgumentNullException.ThrowIfNull(fileName); + ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -191,8 +197,10 @@ public X509Certificate(string fileName!!, SecureString? password, X509KeyStorage } [UnsupportedOSPlatform("browser")] - public X509Certificate(X509Certificate cert!!) + public X509Certificate(X509Certificate cert) { + ArgumentNullException.ThrowIfNull(cert); + if (cert.Pal != null) { Pal = CertificatePal.FromOtherCert(cert); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs index 9bfe38e89d7487..a947635d62a80d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2.cs @@ -429,8 +429,10 @@ public static X509ContentType GetCertContentType(ReadOnlySpan rawData) } [UnsupportedOSPlatform("browser")] - public static X509ContentType GetCertContentType(string fileName!!) + public static X509ContentType GetCertContentType(string fileName) { + ArgumentNullException.ThrowIfNull(fileName); + // .NET Framework compat: The .NET Framework expands the filename to a full path for the purpose of performing a CAS permission check. While CAS is not present here, // we still need to call GetFullPath() so we get the same exception behavior if the fileName is bad. _ = Path.GetFullPath(fileName); @@ -765,8 +767,10 @@ public bool Verify() /// The specified private key doesn't match the public key for this certificate. /// /// - public X509Certificate2 CopyWithPrivateKey(ECDiffieHellman privateKey!!) + public X509Certificate2 CopyWithPrivateKey(ECDiffieHellman privateKey) { + ArgumentNullException.ThrowIfNull(privateKey); + if (HasPrivateKey) throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey); @@ -843,8 +847,10 @@ public X509Certificate2 CopyWithPrivateKey(ECDiffieHellman privateKey!!) /// /// [UnsupportedOSPlatform("browser")] - public static X509Certificate2 CreateFromPemFile(string certPemFilePath!!, string? keyPemFilePath = default) + public static X509Certificate2 CreateFromPemFile(string certPemFilePath, string? keyPemFilePath = default) { + ArgumentNullException.ThrowIfNull(certPemFilePath); + ReadOnlySpan certContents = File.ReadAllText(certPemFilePath); ReadOnlySpan keyContents = keyPemFilePath is null ? certContents : File.ReadAllText(keyPemFilePath); @@ -907,8 +913,10 @@ public static X509Certificate2 CreateFromPemFile(string certPemFilePath!!, strin /// /// [UnsupportedOSPlatform("browser")] - public static X509Certificate2 CreateFromEncryptedPemFile(string certPemFilePath!!, ReadOnlySpan password, string? keyPemFilePath = default) + public static X509Certificate2 CreateFromEncryptedPemFile(string certPemFilePath, ReadOnlySpan password, string? keyPemFilePath = default) { + ArgumentNullException.ThrowIfNull(certPemFilePath); + ReadOnlySpan certContents = File.ReadAllText(certPemFilePath); ReadOnlySpan keyContents = keyPemFilePath is null ? certContents : File.ReadAllText(keyPemFilePath); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2Collection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2Collection.cs index 0fad31798f3b5b..bc202d6bc522fa 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2Collection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate2Collection.cs @@ -44,13 +44,17 @@ public X509Certificate2Collection(X509Certificate2Collection certificates) } } - public int Add(X509Certificate2 certificate!!) + public int Add(X509Certificate2 certificate) { + ArgumentNullException.ThrowIfNull(certificate); + return base.Add(certificate); } - public void AddRange(X509Certificate2[] certificates!!) + public void AddRange(X509Certificate2[] certificates) { + ArgumentNullException.ThrowIfNull(certificates); + int i = 0; try { @@ -69,8 +73,10 @@ public void AddRange(X509Certificate2[] certificates!!) } } - public void AddRange(X509Certificate2Collection certificates!!) + public void AddRange(X509Certificate2Collection certificates) { + ArgumentNullException.ThrowIfNull(certificates); + int i = 0; try { @@ -112,8 +118,10 @@ public bool Contains(X509Certificate2 certificate) } } - public X509Certificate2Collection Find(X509FindType findType, object findValue!!, bool validOnly) + public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly) { + ArgumentNullException.ThrowIfNull(findValue); + return FindPal.FindFromCollection(this, findType, findValue, validOnly); } @@ -124,8 +132,10 @@ public X509Certificate2Collection Find(X509FindType findType, object findValue!! IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public void Import(byte[] rawData!!) + public void Import(byte[] rawData) { + ArgumentNullException.ThrowIfNull(rawData); + Import(rawData.AsSpan()); } @@ -140,8 +150,10 @@ public void Import(ReadOnlySpan rawData) Import(rawData, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet); } - public void Import(byte[] rawData!!, string? password, X509KeyStorageFlags keyStorageFlags = 0) + public void Import(byte[] rawData, string? password, X509KeyStorageFlags keyStorageFlags = 0) { + ArgumentNullException.ThrowIfNull(rawData); + Import(rawData.AsSpan(), password.AsSpan(), keyStorageFlags); } @@ -190,8 +202,10 @@ public void Import(string fileName) Import(fileName, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet); } - public void Import(string fileName!!, string? password, X509KeyStorageFlags keyStorageFlags = 0) + public void Import(string fileName, string? password, X509KeyStorageFlags keyStorageFlags = 0) { + ArgumentNullException.ThrowIfNull(fileName); + X509Certificate.ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -213,8 +227,10 @@ public void Import(string fileName!!, string? password, X509KeyStorageFlags keyS /// /// A bitwise combination of the enumeration values that control where and how to import the certificate. /// - public void Import(string fileName!!, ReadOnlySpan password, X509KeyStorageFlags keyStorageFlags = 0) + public void Import(string fileName, ReadOnlySpan password, X509KeyStorageFlags keyStorageFlags = 0) { + ArgumentNullException.ThrowIfNull(fileName); + X509Certificate.ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -224,18 +240,24 @@ public void Import(string fileName!!, ReadOnlySpan password, X509KeyStorag } } - public void Insert(int index, X509Certificate2 certificate!!) + public void Insert(int index, X509Certificate2 certificate) { + ArgumentNullException.ThrowIfNull(certificate); + base.Insert(index, certificate); } - public void Remove(X509Certificate2 certificate!!) + public void Remove(X509Certificate2 certificate) { + ArgumentNullException.ThrowIfNull(certificate); + base.Remove(certificate); } - public void RemoveRange(X509Certificate2[] certificates!!) + public void RemoveRange(X509Certificate2[] certificates) { + ArgumentNullException.ThrowIfNull(certificates); + int i = 0; try { @@ -254,8 +276,10 @@ public void RemoveRange(X509Certificate2[] certificates!!) } } - public void RemoveRange(X509Certificate2Collection certificates!!) + public void RemoveRange(X509Certificate2Collection certificates) { + ArgumentNullException.ThrowIfNull(certificates); + int i = 0; try { @@ -299,8 +323,10 @@ public void RemoveRange(X509Certificate2Collection certificates!!) /// /// is . /// - public void ImportFromPemFile(string certPemFilePath!!) + public void ImportFromPemFile(string certPemFilePath) { + ArgumentNullException.ThrowIfNull(certPemFilePath); + ReadOnlySpan contents = System.IO.File.ReadAllText(certPemFilePath); ImportFromPem(contents); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs index 2e61f208423d3c..9c342269a29b98 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateCollection.cs @@ -41,16 +41,20 @@ public int Add(X509Certificate value) return List.Add(value); } - public void AddRange(X509Certificate[] value!!) + public void AddRange(X509Certificate[] value) { + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(X509CertificateCollection value!!) + public void AddRange(X509CertificateCollection value) { + ArgumentNullException.ThrowIfNull(value); + for (int i = 0; i < value.Count; i++) { Add(value[i]); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateEnumerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateEnumerator.cs index c99e74abd1d4fd..61801b124108dc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateEnumerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509CertificateEnumerator.cs @@ -11,8 +11,10 @@ public class X509CertificateEnumerator : IEnumerator { private readonly IEnumerator _enumerator; - public X509CertificateEnumerator(X509CertificateCollection mappings!!) + public X509CertificateEnumerator(X509CertificateCollection mappings) { + ArgumentNullException.ThrowIfNull(mappings); + _enumerator = ((IEnumerable)mappings).GetEnumerator(); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ChainElementCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ChainElementCollection.cs index c8aae17f6b0050..b368a3579aabb4 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ChainElementCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ChainElementCollection.cs @@ -55,8 +55,10 @@ public void CopyTo(X509ChainElement[] array, int index) ((ICollection)this).CopyTo(array, index); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509EnhancedKeyUsageExtension.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509EnhancedKeyUsageExtension.cs index 5e7b3b42f99bb1..f90979705b9052 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509EnhancedKeyUsageExtension.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509EnhancedKeyUsageExtension.cs @@ -44,8 +44,10 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) _decoded = false; } - private static byte[] EncodeExtension(OidCollection enhancedKeyUsages!!) + private static byte[] EncodeExtension(OidCollection enhancedKeyUsages) { + ArgumentNullException.ThrowIfNull(enhancedKeyUsages); + return X509Pal.Instance.EncodeX509EnhancedKeyUsageExtension(enhancedKeyUsages); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs index 1b4dd42ceb4bef..fa6a8f8f1e9f11 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs @@ -17,8 +17,8 @@ public X509Extension(AsnEncodedData encodedExtension, bool critical) { } - public X509Extension(Oid oid, byte[] rawData!!, bool critical) - : this(oid, (ReadOnlySpan)rawData, critical) + public X509Extension(Oid oid, byte[] rawData, bool critical) + : this(oid, (ReadOnlySpan)(rawData ?? throw new ArgumentNullException(nameof(rawData))), critical) { } @@ -38,7 +38,7 @@ public X509Extension(Oid oid, byte[] rawData!!, bool critical) public X509Extension(Oid oid, ReadOnlySpan rawData, bool critical) : base(oid, rawData) { - if (base.Oid == null || base.Oid.Value == null) + if (base.Oid?.Value == null) throw new ArgumentNullException(nameof(oid)); if (base.Oid.Value.Length == 0) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid)); @@ -70,8 +70,10 @@ public X509Extension(string oid, ReadOnlySpan rawData, bool critical) public bool Critical { get; set; } - public override void CopyFrom(AsnEncodedData asnEncodedData!!) + public override void CopyFrom(AsnEncodedData asnEncodedData) { + ArgumentNullException.ThrowIfNull(asnEncodedData); + X509Extension? extension = asnEncodedData as X509Extension; if (extension == null) throw new ArgumentException(SR.Cryptography_X509_ExtensionMismatch); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ExtensionCollection.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ExtensionCollection.cs index 44efeb6139a81c..6d3b23d67e7f3f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ExtensionCollection.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509ExtensionCollection.cs @@ -62,8 +62,10 @@ public X509Extension? this[string oid] } } - public int Add(X509Extension extension!!) + public int Add(X509Extension extension) { + ArgumentNullException.ThrowIfNull(extension); + _list.Add(extension); return _list.Count - 1; } @@ -73,8 +75,10 @@ public void CopyTo(X509Extension[] array, int index) ((ICollection)this).CopyTo(array, index); } - void ICollection.CopyTo(Array array!!, int index) + void ICollection.CopyTo(Array array, int index) { + ArgumentNullException.ThrowIfNull(array); + if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs index ddf1962d7ec937..0ba24b4b403555 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SignatureGenerator.cs @@ -24,13 +24,18 @@ public PublicKey PublicKey public abstract byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm); protected abstract PublicKey BuildPublicKey(); - public static X509SignatureGenerator CreateForECDsa(ECDsa key!!) + public static X509SignatureGenerator CreateForECDsa(ECDsa key) { + ArgumentNullException.ThrowIfNull(key); + return new ECDsaX509SignatureGenerator(key); } - public static X509SignatureGenerator CreateForRSA(RSA key!!, RSASignaturePadding signaturePadding!!) + public static X509SignatureGenerator CreateForRSA(RSA key, RSASignaturePadding signaturePadding) { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(signaturePadding); + if (signaturePadding == RSASignaturePadding.Pkcs1) return new RSAPkcs1X509SignatureGenerator(key); if (signaturePadding.Mode == RSASignaturePaddingMode.Pss) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs index 076e88d8fdc25d..0b666f842546fc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Store.cs @@ -126,8 +126,10 @@ public bool IsOpen get { return _storePal != null; } } - public void Add(X509Certificate2 certificate!!) + public void Add(X509Certificate2 certificate) { + ArgumentNullException.ThrowIfNull(certificate); + if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); @@ -137,8 +139,10 @@ public void Add(X509Certificate2 certificate!!) _storePal.Add(certificate.Pal); } - public void AddRange(X509Certificate2Collection certificates!!) + public void AddRange(X509Certificate2Collection certificates) { + ArgumentNullException.ThrowIfNull(certificates); + int i = 0; try { @@ -160,8 +164,10 @@ public void AddRange(X509Certificate2Collection certificates!!) } } - public void Remove(X509Certificate2 certificate!!) + public void Remove(X509Certificate2 certificate) { + ArgumentNullException.ThrowIfNull(certificate); + if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); @@ -171,8 +177,10 @@ public void Remove(X509Certificate2 certificate!!) _storePal.Remove(certificate.Pal); } - public void RemoveRange(X509Certificate2Collection certificates!!) + public void RemoveRange(X509Certificate2Collection certificates) { + ArgumentNullException.ThrowIfNull(certificates); + int i = 0; try { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SubjectKeyIdentifierExtension.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SubjectKeyIdentifierExtension.cs index 32e56d628e8861..fd893ce6d22913 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SubjectKeyIdentifierExtension.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509SubjectKeyIdentifierExtension.cs @@ -19,8 +19,8 @@ public X509SubjectKeyIdentifierExtension(AsnEncodedData encodedSubjectKeyIdentif { } - public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier!!, bool critical) - : this((ReadOnlySpan)subjectKeyIdentifier, critical) + public X509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier, bool critical) + : this((ReadOnlySpan)(subjectKeyIdentifier ?? throw new ArgumentNullException(nameof(subjectKeyIdentifier))), critical) { } @@ -73,14 +73,18 @@ private static byte[] EncodeExtension(ReadOnlySpan subjectKeyIdentifier) return X509Pal.Instance.EncodeX509SubjectKeyIdentifierExtension(subjectKeyIdentifier); } - private static byte[] EncodeExtension(string subjectKeyIdentifier!!) + private static byte[] EncodeExtension(string subjectKeyIdentifier) { + ArgumentNullException.ThrowIfNull(subjectKeyIdentifier); + byte[] subjectKeyIdentifiedBytes = subjectKeyIdentifier.LaxDecodeHexString(); return EncodeExtension(subjectKeyIdentifiedBytes); } - private static byte[] EncodeExtension(PublicKey key!!, X509SubjectKeyIdentifierHashAlgorithm algorithm) + private static byte[] EncodeExtension(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm) { + ArgumentNullException.ThrowIfNull(key); + byte[] subjectKeyIdentifier = GenerateSubjectKeyIdentifierFromPublicKey(key, algorithm); return EncodeExtension(subjectKeyIdentifier); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs index 465d7495881fe0..123812a374d34a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/XmlKeyHelper.cs @@ -12,8 +12,10 @@ namespace System.Security.Cryptography { internal static class XmlKeyHelper { - internal static ParseState ParseDocument(string xmlString!!) + internal static ParseState ParseDocument(string xmlString) { + ArgumentNullException.ThrowIfNull(xmlString); + try { return ParseState.ParseDocument(xmlString); diff --git a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs index f44935f2b7354e..91a3c524c46d3f 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/PrincipalPermission.cs @@ -268,8 +268,13 @@ public SecurityElement ToXml() return root; } - public void FromXml(SecurityElement elem!!) + public void FromXml(SecurityElement elem) { + if (elem is null) + { + throw new ArgumentNullException(nameof(elem)); + } + if (elem.Tag == null || !elem.Tag.Equals("Permission") && !elem.Tag.Equals("IPermission")) throw new ArgumentException(SR.Argument_NotAPermissionElement); diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs index 297b3823d7b7d7..cb8ee40d957074 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/IRCollection.cs @@ -66,13 +66,17 @@ bool ICollection.IsReadOnly } } - public void Add(IdentityReference identity!!) + public void Add(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); + _identities.Add(identity); } - public bool Remove(IdentityReference identity!!) + public bool Remove(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); + if (Contains(identity)) { return _identities.Remove(identity); @@ -86,8 +90,10 @@ public void Clear() _identities.Clear(); } - public bool Contains(IdentityReference identity!!) + public bool Contains(IdentityReference identity) { + ArgumentNullException.ThrowIfNull(identity); + return _identities.Contains(identity); } @@ -136,8 +142,10 @@ public IdentityReferenceCollection Translate(Type targetType) return Translate(targetType, false); } - public IdentityReferenceCollection Translate(Type targetType!!, bool forceSuccess) + public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) { + ArgumentNullException.ThrowIfNull(targetType); + // // Target type must be a subclass of IdentityReference // @@ -371,8 +379,10 @@ internal sealed class IdentityReferenceEnumerator : IEnumerator(SafeAccessTokenHandle safeAccessTokenHandle, Func func!!) + public static T RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Func func) { + ArgumentNullException.ThrowIfNull(func); + T result = default!; RunImpersonatedInternal(safeAccessTokenHandle, () => result = func()); return result; @@ -914,8 +918,10 @@ private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle return safeLocalAllocHandle; } - private static string? GetAuthType(WindowsIdentity identity!!) + private static string? GetAuthType(WindowsIdentity identity) { + ArgumentNullException.ThrowIfNull(identity); + return identity._authType; } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs index e61a27e7b08612..9a25c928a949b1 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs @@ -29,9 +29,11 @@ public class WindowsPrincipal : ClaimsPrincipal // Constructors. // - public WindowsPrincipal(WindowsIdentity ntIdentity!!) + public WindowsPrincipal(WindowsIdentity ntIdentity) : base(ntIdentity) { + ArgumentNullException.ThrowIfNull(ntIdentity); + _identity = ntIdentity; } @@ -132,8 +134,10 @@ public virtual bool IsInRole(int rid) // The aforementioned overloads remain in this class since we do not want to introduce a // breaking change. However, this method should be used in all new applications. - public virtual bool IsInRole(SecurityIdentifier sid!!) + public virtual bool IsInRole(SecurityIdentifier sid) { + ArgumentNullException.ThrowIfNull(sid); + // special case the anonymous identity. if (_identity.AccessToken.IsInvalid) return false; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs index abd8eec43ec108..fd6620844bb462 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs @@ -35,8 +35,13 @@ public Atom10FeedFormatter() : this(typeof(SyndicationFeed)) { } - public Atom10FeedFormatter(Type feedTypeToCreate!!) : base() + public Atom10FeedFormatter(Type feedTypeToCreate) : base() { + if (feedTypeToCreate is null) + { + throw new ArgumentNullException(nameof(feedTypeToCreate)); + } + if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed)), nameof(feedTypeToCreate)); @@ -66,20 +71,35 @@ internal override TryParseDateTimeCallback GetDefaultDateTimeParser() protected Type FeedType { get; } - public override bool CanRead(XmlReader reader!!) + public override bool CanRead(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + return reader.IsStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); } XmlSchema IXmlSerializable.GetSchema() => null; - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + ReadFeed(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer!!) + void IXmlSerializable.WriteXml(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + WriteFeed(writer); } @@ -93,8 +113,13 @@ public override void ReadFrom(XmlReader reader) ReadFeed(reader); } - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + writer.WriteStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); WriteFeed(writer); writer.WriteEndElement(); @@ -469,15 +494,33 @@ internal static void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseU protected override SyndicationFeed CreateFeedInstance() => CreateFeedInstance(FeedType); - protected virtual SyndicationItem ReadItem(XmlReader reader!!, SyndicationFeed feed!!) + protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + SyndicationItem item = CreateItem(feed); ReadItemFrom(reader, item, feed.BaseUri); return item; } - protected virtual IEnumerable ReadItems(XmlReader reader!!, SyndicationFeed feed!!, out bool areAllItemsRead) + protected virtual IEnumerable ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + NullNotAllowedCollection items = new NullNotAllowedCollection(); while (reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace)) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs index 97b31b6f09822d..a3d2733882bafc 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs @@ -19,8 +19,13 @@ public Atom10ItemFormatter() : this(typeof(SyndicationItem)) { } - public Atom10ItemFormatter(Type itemTypeToCreate!!) : base() + public Atom10ItemFormatter(Type itemTypeToCreate) : base() { + if (itemTypeToCreate is null) + { + throw new ArgumentNullException(nameof(itemTypeToCreate)); + } + if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(itemTypeToCreate), nameof(SyndicationItem)), nameof(itemTypeToCreate)); @@ -58,20 +63,35 @@ public bool PreserveElementExtensions protected Type ItemType { get; } - public override bool CanRead(XmlReader reader!!) + public override bool CanRead(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + return reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace); } XmlSchema IXmlSerializable.GetSchema() => null; - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + ReadItem(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer!!) + void IXmlSerializable.WriteXml(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + WriteItem(writer); } @@ -85,8 +105,13 @@ public override void ReadFrom(XmlReader reader) ReadItem(reader); } - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + writer.WriteStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace); WriteItem(writer); writer.WriteEndElement(); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs index 8c120f4be97e79..908ff31ec9db0d 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs @@ -60,20 +60,35 @@ public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite) public override string Version => App10Constants.Namespace; - public override bool CanRead(XmlReader reader!!) + public override bool CanRead(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + return reader.IsStartElement(App10Constants.Categories, App10Constants.Namespace); } XmlSchema IXmlSerializable.GetSchema() => null; - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + ReadDocument(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer!!) + void IXmlSerializable.WriteXml(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); @@ -82,8 +97,13 @@ void IXmlSerializable.WriteXml(XmlWriter writer!!) WriteDocument(writer); } - public override void ReadFrom(XmlReader reader!!) + public override void ReadFrom(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + if (!CanRead(reader)) { throw new XmlException(SR.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI)); @@ -92,8 +112,13 @@ public override void ReadFrom(XmlReader reader!!) ReadDocument(reader); } - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs index 9d80b98b2fdb1c..b37e04b1344e5c 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs @@ -22,8 +22,13 @@ public AtomPub10ServiceDocumentFormatter() : this(typeof(ServiceDocument)) { } - public AtomPub10ServiceDocumentFormatter(Type documentTypeToCreate!!) : base() + public AtomPub10ServiceDocumentFormatter(Type documentTypeToCreate) : base() { + if (documentTypeToCreate is null) + { + throw new ArgumentNullException(nameof(documentTypeToCreate)); + } + if (!typeof(ServiceDocument).IsAssignableFrom(documentTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(documentTypeToCreate), nameof(ServiceDocument)), nameof(documentTypeToCreate)); @@ -41,20 +46,35 @@ public AtomPub10ServiceDocumentFormatter(ServiceDocument documentToWrite) : base public override string Version => App10Constants.Namespace; - public override bool CanRead(XmlReader reader!!) + public override bool CanRead(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + return reader.IsStartElement(App10Constants.Service, App10Constants.Namespace); } XmlSchema IXmlSerializable.GetSchema() => null; - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + ReadDocument(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer!!) + void IXmlSerializable.WriteXml(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); @@ -63,8 +83,13 @@ void IXmlSerializable.WriteXml(XmlWriter writer!!) WriteDocument(writer); } - public override void ReadFrom(XmlReader reader!!) + public override void ReadFrom(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + reader.MoveToContent(); if (!CanRead(reader)) { @@ -74,8 +99,13 @@ public override void ReadFrom(XmlReader reader!!) ReadDocument(reader); } - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs index f0c4c72796b426..078aaad3def526 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs @@ -15,8 +15,13 @@ protected CategoriesDocumentFormatter() { } - protected CategoriesDocumentFormatter(CategoriesDocument documentToWrite!!) + protected CategoriesDocumentFormatter(CategoriesDocument documentToWrite) { + if (documentToWrite is null) + { + throw new ArgumentNullException(nameof(documentToWrite)); + } + _document = documentToWrite; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs index d31e5d5319b901..0e1994e537d345 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs @@ -63,8 +63,13 @@ private static XmlBuffer CreateXmlBuffer(XmlDictionaryReader unparsedExtensionsR return buffer; } - internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions!!, int maxExtensionSize) + internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) { + if (readerOverUnparsedExtensions is null) + { + throw new ArgumentNullException(nameof(readerOverUnparsedExtensions)); + } + if (maxExtensionSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxExtensionSize)); @@ -80,8 +85,13 @@ internal void LoadElementExtensions(XmlBuffer buffer) _elementExtensions = new SyndicationElementExtensionCollection(buffer); } - internal void WriteAttributeExtensions(XmlWriter writer!!) + internal void WriteAttributeExtensions(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (_attributeExtensions != null) { foreach (XmlQualifiedName qname in _attributeExtensions.Keys) @@ -92,8 +102,13 @@ internal void WriteAttributeExtensions(XmlWriter writer!!) } } - internal void WriteElementExtensions(XmlWriter writer!!, Func shouldSkipElement = null) + internal void WriteElementExtensions(XmlWriter writer, Func shouldSkipElement = null) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (_elementExtensions != null) { _elementExtensions.WriteTo(writer, shouldSkipElement); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs index d20e5f50114f3a..a33013931078aa 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs @@ -11,13 +11,23 @@ public NullNotAllowedCollection() : base() { } - protected override void InsertItem(int index, TCollectionItem item!!) + protected override void InsertItem(int index, TCollectionItem item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + base.InsertItem(index, item); } - protected override void SetItem(int index, TCollectionItem item!!) + protected override void SetItem(int index, TCollectionItem item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + base.SetItem(index, item); } } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs index 3112de805bf7dc..ac4eecb766f1cc 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs @@ -9,8 +9,13 @@ public ReferencedCategoriesDocument() { } - public ReferencedCategoriesDocument(Uri link!!) : base() + public ReferencedCategoriesDocument(Uri link) : base() { + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + Link = link; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs index 6bed1833f1311a..5610de3e018e12 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs @@ -31,8 +31,17 @@ public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerabl { } - public ResourceCollectionInfo(TextSyndicationContent title!!, Uri link!!, IEnumerable categories, IEnumerable accepts) + public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerable categories, IEnumerable accepts) { + if (title is null) + { + throw new ArgumentNullException(nameof(title)); + } + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + Title = title; Link = link; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs index f593d160baee49..97e5aef050da02 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs @@ -30,8 +30,13 @@ public Rss20FeedFormatter() : this(typeof(SyndicationFeed)) { } - public Rss20FeedFormatter(Type feedTypeToCreate!!) : base() + public Rss20FeedFormatter(Type feedTypeToCreate) : base() { + if (feedTypeToCreate is null) + { + throw new ArgumentNullException(nameof(feedTypeToCreate)); + } + if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed)), nameof(feedTypeToCreate)); @@ -68,20 +73,35 @@ public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsA protected Type FeedType { get; } - public override bool CanRead(XmlReader reader!!) + public override bool CanRead(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + return reader.IsStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); } XmlSchema IXmlSerializable.GetSchema() => null; - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + ReadFeed(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer!!) + void IXmlSerializable.WriteXml(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + WriteFeed(writer); } @@ -95,8 +115,13 @@ public override void ReadFrom(XmlReader reader) ReadFeed(reader); } - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + writer.WriteStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); WriteFeed(writer); writer.WriteEndElement(); @@ -120,15 +145,33 @@ internal void WriteItemContents(XmlWriter writer, SyndicationItem item) protected override SyndicationFeed CreateFeedInstance() => CreateFeedInstance(FeedType); - protected virtual SyndicationItem ReadItem(XmlReader reader!!, SyndicationFeed feed!!) + protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + SyndicationItem item = CreateItem(feed); ReadItemFrom(reader, item, feed.BaseUri); return item; } - protected virtual IEnumerable ReadItems(XmlReader reader!!, SyndicationFeed feed!!, out bool areAllItemsRead) + protected virtual IEnumerable ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + NullNotAllowedCollection items = new NullNotAllowedCollection(); while (reader.IsStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace)) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs index b29f46d382968c..672e30f3a08df0 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs @@ -20,8 +20,13 @@ public Rss20ItemFormatter() : this(typeof(SyndicationItem)) { } - public Rss20ItemFormatter(Type itemTypeToCreate!!) : base() + public Rss20ItemFormatter(Type itemTypeToCreate) : base() { + if (itemTypeToCreate is null) + { + throw new ArgumentNullException(nameof(itemTypeToCreate)); + } + if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(itemTypeToCreate), nameof(SyndicationItem)), nameof(itemTypeToCreate)); @@ -81,20 +86,35 @@ public bool SerializeExtensionsAsAtom protected Type ItemType { get; } - public override bool CanRead(XmlReader reader!!) + public override bool CanRead(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + return reader.IsStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); } XmlSchema IXmlSerializable.GetSchema() => null; - void IXmlSerializable.ReadXml(XmlReader reader!!) + void IXmlSerializable.ReadXml(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + ReadItem(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer!!) + void IXmlSerializable.WriteXml(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + WriteItem(writer); } @@ -108,8 +128,13 @@ public override void ReadFrom(XmlReader reader) ReadItem(reader); } - public override void WriteTo(XmlWriter writer!!) + public override void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + writer.WriteStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace); WriteItem(writer); writer.WriteEndElement(); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs index 66319f9214a200..bd5ace62f4a086 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs @@ -16,8 +16,13 @@ protected ServiceDocumentFormatter() { } - protected ServiceDocumentFormatter(ServiceDocument documentToWrite!!) + protected ServiceDocumentFormatter(ServiceDocument documentToWrite) { + if (documentToWrite is null) + { + throw new ArgumentNullException(nameof(documentToWrite)); + } + _document = documentToWrite; } @@ -53,19 +58,34 @@ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter workspace.LoadElementExtensions(buffer); } - internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document!!) + internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + SyndicationFeedFormatter.CloseBuffer(buffer, writer); document.LoadElementExtensions(buffer); } - protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories!!) + protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories) { + if (inlineCategories is null) + { + throw new ArgumentNullException(nameof(inlineCategories)); + } + return inlineCategories.CreateCategory(); } - protected static ResourceCollectionInfo CreateCollection(Workspace workspace!!) + protected static ResourceCollectionInfo CreateCollection(Workspace workspace) { + if (workspace is null) + { + throw new ArgumentNullException(nameof(workspace)); + } + return workspace.CreateResourceCollection(); } @@ -79,108 +99,213 @@ protected static ReferencedCategoriesDocument CreateReferencedCategories(Resourc return collection.CreateReferencedCategoriesDocument(); } - protected static Workspace CreateWorkspace(ServiceDocument document!!) + protected static Workspace CreateWorkspace(ServiceDocument document) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + return document.CreateWorkspace(); } - protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories!!, int maxExtensionSize) + protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize) { + if (categories is null) + { + throw new ArgumentNullException(nameof(categories)); + } + categories.LoadElementExtensions(reader, maxExtensionSize); } - protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection!!, int maxExtensionSize) + protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize) { + if (collection is null) + { + throw new ArgumentNullException(nameof(collection)); + } + collection.LoadElementExtensions(reader, maxExtensionSize); } - protected static void LoadElementExtensions(XmlReader reader, Workspace workspace!!, int maxExtensionSize) + protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize) { + if (workspace is null) + { + throw new ArgumentNullException(nameof(workspace)); + } + workspace.LoadElementExtensions(reader, maxExtensionSize); } - protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document!!, int maxExtensionSize) + protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + document.LoadElementExtensions(reader, maxExtensionSize); } - protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document!!, string version) + protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + return document.TryParseAttribute(name, ns, value, version); } - protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection!!, string version) + protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version) { + if (collection is null) + { + throw new ArgumentNullException(nameof(collection)); + } + return collection.TryParseAttribute(name, ns, value, version); } - protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories!!, string version) + protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version) { + if (categories is null) + { + throw new ArgumentNullException(nameof(categories)); + } + return categories.TryParseAttribute(name, ns, value, version); } - protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace!!, string version) + protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version) { + if (workspace is null) + { + throw new ArgumentNullException(nameof(workspace)); + } + return workspace.TryParseAttribute(name, ns, value, version); } - protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection!!, string version) + protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version) { + if (collection is null) + { + throw new ArgumentNullException(nameof(collection)); + } + return collection.TryParseElement(reader, version); } - protected static bool TryParseElement(XmlReader reader, ServiceDocument document!!, string version) + protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + return document.TryParseElement(reader, version); } - protected static bool TryParseElement(XmlReader reader, Workspace workspace!!, string version) + protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version) { + if (workspace is null) + { + throw new ArgumentNullException(nameof(workspace)); + } + return workspace.TryParseElement(reader, version); } - protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories!!, string version) + protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version) { + if (categories is null) + { + throw new ArgumentNullException(nameof(categories)); + } + return categories.TryParseElement(reader, version); } - protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document!!, string version) + protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + document.WriteAttributeExtensions(writer, version); } - protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace!!, string version) + protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version) { + if (workspace is null) + { + throw new ArgumentNullException(nameof(workspace)); + } + workspace.WriteAttributeExtensions(writer, version); } - protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection!!, string version) + protected static void WriteAttributeExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { + if (collection is null) + { + throw new ArgumentNullException(nameof(collection)); + } + collection.WriteAttributeExtensions(writer, version); } - protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories!!, string version) + protected static void WriteAttributeExtensions(XmlWriter writer, CategoriesDocument categories, string version) { + if (categories is null) + { + throw new ArgumentNullException(nameof(categories)); + } + categories.WriteAttributeExtensions(writer, version); } - protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document!!, string version) + protected static void WriteElementExtensions(XmlWriter writer, ServiceDocument document, string version) { + if (document is null) + { + throw new ArgumentNullException(nameof(document)); + } + document.WriteElementExtensions(writer, version); } - protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace!!, string version) + protected static void WriteElementExtensions(XmlWriter writer, Workspace workspace, string version) { + if (workspace is null) + { + throw new ArgumentNullException(nameof(workspace)); + } + workspace.WriteElementExtensions(writer, version); } - protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection!!, string version) + protected static void WriteElementExtensions(XmlWriter writer, ResourceCollectionInfo collection, string version) { + if (collection is null) + { + throw new ArgumentNullException(nameof(collection)); + } + collection.WriteElementExtensions(writer, version); } - protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories!!, string version) + protected static void WriteElementExtensions(XmlWriter writer, CategoriesDocument categories, string version) { + if (categories is null) + { + throw new ArgumentNullException(nameof(categories)); + } + categories.WriteElementExtensions(writer, version); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs index 0a25117ee8203e..c34a502b75fb2b 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs @@ -26,8 +26,13 @@ public SyndicationCategory(string name, string scheme, string label) Label = label; } - protected SyndicationCategory(SyndicationCategory source!!) + protected SyndicationCategory(SyndicationCategory source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + Label = source.Label; Name = source.Name; Scheme = source.Scheme; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs index 41d588b56e3f7c..bea4b91efeec92 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs @@ -67,8 +67,13 @@ public static XmlSyndicationContent CreateXmlContent(object xmlSerializerObject, public abstract SyndicationContent Clone(); - public void WriteTo(XmlWriter writer!!, string outerElementName, string outerElementNamespace) + public void WriteTo(XmlWriter writer, string outerElementName, string outerElementNamespace) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (string.IsNullOrEmpty(outerElementName)) { throw new ArgumentException(SR.OuterElementNameNotSpecified, nameof(outerElementName)); @@ -92,8 +97,13 @@ public void WriteTo(XmlWriter writer!!, string outerElementName, string outerEle writer.WriteEndElement(); } - internal void CopyAttributeExtensions(SyndicationContent source!!) + internal void CopyAttributeExtensions(SyndicationContent source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + if (source._attributeExtensions != null) { foreach (XmlQualifiedName key in source._attributeExtensions.Keys) diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs index 32c1855a92a1ac..df531efa6965e5 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs @@ -19,8 +19,13 @@ public class SyndicationElementExtension private string _outerName; private string _outerNamespace; - public SyndicationElementExtension(XmlReader xmlReader!!) + public SyndicationElementExtension(XmlReader xmlReader) { + if (xmlReader is null) + { + throw new ArgumentNullException(nameof(xmlReader)); + } + SyndicationFeedFormatter.MoveToStartElement(xmlReader); _outerName = xmlReader.LocalName; _outerNamespace = xmlReader.NamespaceURI; @@ -50,8 +55,13 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje { } - public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension!!, XmlObjectSerializer dataContractSerializer) + public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { + if (dataContractExtension is null) + { + throw new ArgumentNullException(nameof(dataContractExtension)); + } + if (outerName == string.Empty) { throw new ArgumentException(SR.OuterNameOfElementExtensionEmpty, nameof(outerName)); @@ -67,8 +77,13 @@ public SyndicationElementExtension(string outerName, string outerNamespace, obje _extensionDataWriter = new ExtensionDataWriter(_extensionData, dataContractSerializer, _outerName, _outerNamespace); } - public SyndicationElementExtension(object xmlSerializerExtension!!, XmlSerializer serializer) + public SyndicationElementExtension(object xmlSerializerExtension, XmlSerializer serializer) { + if (xmlSerializerExtension is null) + { + throw new ArgumentNullException(nameof(xmlSerializerExtension)); + } + if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); @@ -113,8 +128,13 @@ public string OuterNamespace public TExtension GetObject() => GetObject(new DataContractSerializer(typeof(TExtension))); - public TExtension GetObject(XmlObjectSerializer serializer!!) + public TExtension GetObject(XmlObjectSerializer serializer) { + if (serializer is null) + { + throw new ArgumentNullException(nameof(serializer)); + } + if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; @@ -125,8 +145,13 @@ public TExtension GetObject(XmlObjectSerializer serializer!!) } } - public TExtension GetObject(XmlSerializer serializer!!) + public TExtension GetObject(XmlSerializer serializer) { + if (serializer is null) + { + throw new ArgumentNullException(nameof(serializer)); + } + if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; @@ -155,8 +180,13 @@ public XmlReader GetReader() return reader; } - public void WriteTo(XmlWriter writer!!) + public void WriteTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (_extensionDataWriter != null) { _extensionDataWriter.WriteTo(writer); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs index e99e7386b1e745..3188e572a78c35 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs @@ -61,8 +61,13 @@ public void Add(object dataContractExtension, DataContractSerializer serializer) Add(null, null, dataContractExtension, serializer); } - public void Add(string outerName, string outerNamespace, object dataContractExtension!!, XmlObjectSerializer dataContractSerializer) + public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer) { + if (dataContractExtension is null) + { + throw new ArgumentNullException(nameof(dataContractExtension)); + } + if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); @@ -70,8 +75,13 @@ public void Add(string outerName, string outerNamespace, object dataContractExte base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer)); } - public void Add(object xmlSerializerExtension!!, XmlSerializer serializer) + public void Add(object xmlSerializerExtension, XmlSerializer serializer) { + if (xmlSerializerExtension is null) + { + throw new ArgumentNullException(nameof(xmlSerializerExtension)); + } + if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); @@ -79,8 +89,13 @@ public void Add(object xmlSerializerExtension!!, XmlSerializer serializer) base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer)); } - public void Add(XmlReader xmlReader!!) + public void Add(XmlReader xmlReader) { + if (xmlReader is null) + { + throw new ArgumentNullException(nameof(xmlReader)); + } + base.Add(new SyndicationElementExtension(xmlReader)); } @@ -97,13 +112,23 @@ public Collection ReadElementExtensions(string extension return ReadElementExtensions(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension))); } - public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlObjectSerializer serializer!!) + public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlObjectSerializer serializer) { + if (serializer is null) + { + throw new ArgumentNullException(nameof(serializer)); + } + return ReadExtensions(extensionName, extensionNamespace, serializer, null); } - public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlSerializer serializer!!) + public Collection ReadElementExtensions(string extensionName, string extensionNamespace, XmlSerializer serializer) { + if (serializer is null) + { + throw new ArgumentNullException(nameof(serializer)); + } + return ReadExtensions(extensionName, extensionNamespace, null, serializer); } @@ -143,8 +168,13 @@ protected override void ClearItems() _buffer = null; } - protected override void InsertItem(int index, SyndicationElementExtension item!!) + protected override void InsertItem(int index, SyndicationElementExtension item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) @@ -161,8 +191,13 @@ protected override void RemoveItem(int index) _buffer = null; } - protected override void SetItem(int index, SyndicationElementExtension item!!) + protected override void SetItem(int index, SyndicationElementExtension item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + base.SetItem(index, item); Debug.Assert(_initialized, "The constructor should never set items in the collection."); _buffer = null; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs index eec10c931bd98b..47205d3f8c84ff 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs @@ -67,8 +67,13 @@ public SyndicationFeed(string title, string description, Uri feedAlternateLink, _items = items; } - protected SyndicationFeed(SyndicationFeed source!!, bool cloneItems) + protected SyndicationFeed(SyndicationFeed source, bool cloneItems) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); _contributors = FeedUtils.ClonePersons(source._contributors); @@ -404,8 +409,13 @@ private static bool IsValidTextInput(SyndicationTextInput textInput) public static SyndicationFeed Load(XmlReader reader) => Load(reader); - public static TSyndicationFeed Load(XmlReader reader!!) where TSyndicationFeed : SyndicationFeed, new() + public static TSyndicationFeed Load(XmlReader reader) where TSyndicationFeed : SyndicationFeed, new() { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + Atom10FeedFormatter atomSerializer = new Atom10FeedFormatter(); if (atomSerializer.CanRead(reader)) { diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs index 019f0007b1f736..b3e631745fd43d 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs @@ -22,8 +22,13 @@ protected SyndicationFeedFormatter() DateTimeParser = GetDefaultDateTimeParser(); } - protected SyndicationFeedFormatter(SyndicationFeed feedToWrite!!) + protected SyndicationFeedFormatter(SyndicationFeed feedToWrite) { + if (feedToWrite is null) + { + throw new ArgumentNullException(nameof(feedToWrite)); + } + _feed = feedToWrite; DateTimeParser = GetDefaultDateTimeParser(); } @@ -53,68 +58,133 @@ private bool NotImplementedDateTimeParser(XmlDateTimeData XmlDateTimeData, out D public abstract void WriteTo(XmlWriter writer); - protected internal static SyndicationCategory CreateCategory(SyndicationFeed feed!!) + protected internal static SyndicationCategory CreateCategory(SyndicationFeed feed) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + return GetNonNullValue(feed.CreateCategory(), SR.FeedCreatedNullCategory); } - protected internal static SyndicationCategory CreateCategory(SyndicationItem item!!) + protected internal static SyndicationCategory CreateCategory(SyndicationItem item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + return GetNonNullValue(item.CreateCategory(), SR.ItemCreatedNullCategory); } - protected internal static SyndicationItem CreateItem(SyndicationFeed feed!!) + protected internal static SyndicationItem CreateItem(SyndicationFeed feed) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + return GetNonNullValue(feed.CreateItem(), SR.FeedCreatedNullItem); } - protected internal static SyndicationLink CreateLink(SyndicationFeed feed!!) + protected internal static SyndicationLink CreateLink(SyndicationFeed feed) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + return GetNonNullValue(feed.CreateLink(), SR.FeedCreatedNullPerson); } - protected internal static SyndicationLink CreateLink(SyndicationItem item!!) + protected internal static SyndicationLink CreateLink(SyndicationItem item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + return GetNonNullValue(item.CreateLink(), SR.ItemCreatedNullPerson); } - protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed!!) + protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + return GetNonNullValue(feed.CreatePerson(), SR.FeedCreatedNullPerson); } - protected internal static SyndicationPerson CreatePerson(SyndicationItem item!!) + protected internal static SyndicationPerson CreatePerson(SyndicationItem item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + return GetNonNullValue(item.CreatePerson(), SR.ItemCreatedNullPerson); } - protected internal static void LoadElementExtensions(XmlReader reader, SyndicationFeed feed!!, int maxExtensionSize) + protected internal static void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + feed.LoadElementExtensions(reader, maxExtensionSize); } - protected internal static void LoadElementExtensions(XmlReader reader, SyndicationItem item!!, int maxExtensionSize) + protected internal static void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + item.LoadElementExtensions(reader, maxExtensionSize); } - protected internal static void LoadElementExtensions(XmlReader reader, SyndicationCategory category!!, int maxExtensionSize) + protected internal static void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize) { + if (category is null) + { + throw new ArgumentNullException(nameof(category)); + } + category.LoadElementExtensions(reader, maxExtensionSize); } - protected internal static void LoadElementExtensions(XmlReader reader, SyndicationLink link!!, int maxExtensionSize) + protected internal static void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize) { + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + link.LoadElementExtensions(reader, maxExtensionSize); } - protected internal static void LoadElementExtensions(XmlReader reader, SyndicationPerson person!!, int maxExtensionSize) + protected internal static void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize) { + if (person is null) + { + throw new ArgumentNullException(nameof(person)); + } + person.LoadElementExtensions(reader, maxExtensionSize); } - protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed!!, string version) + protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -122,8 +192,13 @@ protected internal static bool TryParseAttribute(string name, string ns, string return feed.TryParseAttribute(name, ns, value, version); } - protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item!!, string version) + protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -131,8 +206,13 @@ protected internal static bool TryParseAttribute(string name, string ns, string return item.TryParseAttribute(name, ns, value, version); } - protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category!!, string version) + protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version) { + if (category is null) + { + throw new ArgumentNullException(nameof(category)); + } + if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -140,8 +220,13 @@ protected internal static bool TryParseAttribute(string name, string ns, string return category.TryParseAttribute(name, ns, value, version); } - protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link!!, string version) + protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version) { + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -149,8 +234,13 @@ protected internal static bool TryParseAttribute(string name, string ns, string return link.TryParseAttribute(name, ns, value, version); } - protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person!!, string version) + protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version) { + if (person is null) + { + throw new ArgumentNullException(nameof(person)); + } + if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -163,83 +253,163 @@ protected internal static bool TryParseContent(XmlReader reader, SyndicationItem return item.TryParseContent(reader, contentType, version, out content); } - protected internal static bool TryParseElement(XmlReader reader, SyndicationFeed feed!!, string version) + protected internal static bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + return feed.TryParseElement(reader, version); } - protected internal static bool TryParseElement(XmlReader reader, SyndicationItem item!!, string version) + protected internal static bool TryParseElement(XmlReader reader, SyndicationItem item, string version) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + return item.TryParseElement(reader, version); } - protected internal static bool TryParseElement(XmlReader reader, SyndicationCategory category!!, string version) + protected internal static bool TryParseElement(XmlReader reader, SyndicationCategory category, string version) { + if (category is null) + { + throw new ArgumentNullException(nameof(category)); + } + return category.TryParseElement(reader, version); } - protected internal static bool TryParseElement(XmlReader reader, SyndicationLink link!!, string version) + protected internal static bool TryParseElement(XmlReader reader, SyndicationLink link, string version) { + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + return link.TryParseElement(reader, version); } - protected internal static bool TryParseElement(XmlReader reader, SyndicationPerson person!!, string version) + protected internal static bool TryParseElement(XmlReader reader, SyndicationPerson person, string version) { + if (person is null) + { + throw new ArgumentNullException(nameof(person)); + } + return person.TryParseElement(reader, version); } - protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed!!, string version) + protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationFeed feed, string version) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + feed.WriteAttributeExtensions(writer, version); } - protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item!!, string version) + protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationItem item, string version) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + item.WriteAttributeExtensions(writer, version); } - protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category!!, string version) + protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationCategory category, string version) { + if (category is null) + { + throw new ArgumentNullException(nameof(category)); + } + category.WriteAttributeExtensions(writer, version); } - protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link!!, string version) + protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version) { + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + link.WriteAttributeExtensions(writer, version); } - protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person!!, string version) + protected internal static void WriteAttributeExtensions(XmlWriter writer, SyndicationPerson person, string version) { + if (person is null) + { + throw new ArgumentNullException(nameof(person)); + } + person.WriteAttributeExtensions(writer, version); } - protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed!!, string version) + protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationFeed feed, string version) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + feed.WriteElementExtensions(writer, version); } - protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationItem item!!, string version) + protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationItem item, string version) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + item.WriteElementExtensions(writer, version); } - protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationCategory category!!, string version) + protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationCategory category, string version) { + if (category is null) + { + throw new ArgumentNullException(nameof(category)); + } + category.WriteElementExtensions(writer, version); } - protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationLink link!!, string version) + protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationLink link, string version) { + if (link is null) + { + throw new ArgumentNullException(nameof(link)); + } + link.WriteElementExtensions(writer, version); } - protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationPerson person!!, string version) + protected internal static void WriteElementExtensions(XmlWriter writer, SyndicationPerson person, string version) { + if (person is null) + { + throw new ArgumentNullException(nameof(person)); + } + person.WriteElementExtensions(writer, version); } - protected internal virtual void SetFeed(SyndicationFeed feed!!) + protected internal virtual void SetFeed(SyndicationFeed feed) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + _feed = feed; } @@ -339,8 +509,13 @@ internal static SyndicationFeed CreateFeedInstance(Type feedType) } } - internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed!!) + internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed) { + if (feed is null) + { + throw new ArgumentNullException(nameof(feed)); + } + CloseBuffer(buffer, writer); feed.LoadElementExtensions(buffer); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs index 8ea608f69c1a98..6af70d5cf1717d 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs @@ -48,8 +48,13 @@ public SyndicationItem(string title, SyndicationContent content, Uri itemAlterna _lastUpdatedTime = lastUpdatedTime; } - protected SyndicationItem(SyndicationItem source!!) + protected SyndicationItem(SyndicationItem source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + _extensions = source._extensions.Clone(); _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); @@ -150,8 +155,13 @@ public DateTimeOffset PublishDate public static SyndicationItem Load(XmlReader reader) => Load(reader); - public static TSyndicationItem Load(XmlReader reader!!) where TSyndicationItem : SyndicationItem, new() + public static TSyndicationItem Load(XmlReader reader) where TSyndicationItem : SyndicationItem, new() { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + Atom10ItemFormatter atomSerializer = new Atom10ItemFormatter(); if (atomSerializer.CanRead(reader)) { @@ -169,8 +179,13 @@ public DateTimeOffset PublishDate } - public void AddPermalink(Uri permalink!!) + public void AddPermalink(Uri permalink) { + if (permalink is null) + { + throw new ArgumentNullException(nameof(permalink)); + } + Id = permalink.AbsoluteUri; Links.Add(SyndicationLink.CreateAlternateLink(permalink)); } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs index 9c7e95760c3a0c..6cd3b8c9886fe2 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs @@ -16,8 +16,13 @@ protected SyndicationItemFormatter() _item = null; } - protected SyndicationItemFormatter(SyndicationItem itemToWrite!!) + protected SyndicationItemFormatter(SyndicationItem itemToWrite) { + if (itemToWrite is null) + { + throw new ArgumentNullException(nameof(itemToWrite)); + } + _item = itemToWrite; } @@ -33,8 +38,13 @@ protected SyndicationItemFormatter(SyndicationItem itemToWrite!!) public abstract void WriteTo(XmlWriter writer); - protected internal virtual void SetItem(SyndicationItem item!!) + protected internal virtual void SetItem(SyndicationItem item) { + if (item is null) + { + throw new ArgumentNullException(nameof(item)); + } + _item = item; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs index 62ffbafd572201..cfcb1efa5a746b 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs @@ -35,8 +35,13 @@ public SyndicationLink() : this(null, null, null, null, 0) { } - protected SyndicationLink(SyndicationLink source!!) + protected SyndicationLink(SyndicationLink source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + _length = source._length; MediaType = source.MediaType; RelationshipType = source.RelationshipType; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs index 6c4750aa163f1d..cc76fb2bb6d95f 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs @@ -27,8 +27,13 @@ public SyndicationPerson(string email, string name, string uri) Uri = uri; } - protected SyndicationPerson(SyndicationPerson source!!) + protected SyndicationPerson(SyndicationPerson source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + Email = source.Email; Name = source.Name; Uri = source.Uri; diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs index 19b2a8012b4c32..f42e33222ad3fb 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs @@ -11,8 +11,13 @@ public class UrlSyndicationContent : SyndicationContent { private readonly string _mediaType; - public UrlSyndicationContent(Uri url!!, string mediaType) : base() + public UrlSyndicationContent(Uri url, string mediaType) : base() { + if (url is null) + { + throw new ArgumentNullException(nameof(url)); + } + Url = url; _mediaType = mediaType; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs index b8427a6b642069..e7ba697b8dfebe 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs @@ -17,8 +17,13 @@ public class XmlSyndicationContent : SyndicationContent // Saves the element in the reader to the buffer (attributes preserved) // Type is populated from type attribute on reader // Reader must be positioned at an element - public XmlSyndicationContent(XmlReader reader!!) + public XmlSyndicationContent(XmlReader reader) { + if (reader is null) + { + throw new ArgumentNullException(nameof(reader)); + } + SyndicationFeedFormatter.MoveToStartElement(reader); if (reader.HasAttributes) { @@ -60,8 +65,13 @@ public XmlSyndicationContent(string type, object xmlSerializerExtension, XmlSeri Extension = new SyndicationElementExtension(xmlSerializerExtension, serializer); } - public XmlSyndicationContent(string type, SyndicationElementExtension extension!!) + public XmlSyndicationContent(string type, SyndicationElementExtension extension) { + if (extension is null) + { + throw new ArgumentNullException(nameof(extension)); + } + _type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type; Extension = extension; } @@ -133,8 +143,13 @@ public TContent ReadContent(XmlSerializer serializer) } // does not write start element or type attribute, writes other attributes and rest of content - protected override void WriteContentsTo(XmlWriter writer!!) + protected override void WriteContentsTo(XmlWriter writer) { + if (writer is null) + { + throw new ArgumentNullException(nameof(writer)); + } + if (Extension != null) { Extension.WriteTo(writer); diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs index b1819d0a2ef6fb..088c41cd3fe788 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -867,8 +867,10 @@ public void Start() /// /// Starts a service in the machine specified. /// - public void Start(string[] args!!) + public void Start(string[] args) { + ArgumentNullException.ThrowIfNull(args); + using SafeServiceHandle serviceHandle = GetServiceHandle(Interop.Advapi32.ServiceOptions.SERVICE_START); IntPtr[] argPtrs = new IntPtr[args.Length]; int i = 0; diff --git a/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs b/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs index 0d06bd42d072de..686d0e1593bc8b 100644 --- a/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs +++ b/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs @@ -15,9 +15,11 @@ internal class ObjectToken : RegistryDataKey, ISpObjectToken { #region Constructors - protected ObjectToken(ISpObjectToken sapiObjectToken!!, bool disposeSapiToken) + protected ObjectToken(ISpObjectToken sapiObjectToken, bool disposeSapiToken) : base(sapiObjectToken) { + ArgumentNullException.ThrowIfNull(sapiObjectToken); + _sapiObjectToken = sapiObjectToken; _disposeSapiObjectToken = disposeSapiToken; } diff --git a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs index bed2dfe68d6d42..3b0f2e17b59fd5 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs @@ -22,8 +22,10 @@ public void Add(params SrgsRule[] rules) base.Add(rules[iRule]); } } - protected override string GetKeyForItem(SrgsRule rule!!) + protected override string GetKeyForItem(SrgsRule rule) { + ArgumentNullException.ThrowIfNull(rule); + return rule.Id; } } diff --git a/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs b/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs index 189a16cf8c3007..6fe2156834919e 100644 --- a/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs +++ b/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs @@ -16,8 +16,10 @@ public class RecognizedWordUnit #pragma warning disable 6507 // Constructor for recognized 'word' - public RecognizedWordUnit(string text, float confidence, string pronunciation, string lexicalForm!!, DisplayAttributes displayAttributes, TimeSpan audioPosition, TimeSpan audioDuration) + public RecognizedWordUnit(string text, float confidence, string pronunciation, string lexicalForm, DisplayAttributes displayAttributes, TimeSpan audioPosition, TimeSpan audioDuration) { + ArgumentNullException.ThrowIfNull(lexicalForm); + if (confidence < 0.0f || confidence > 1.0f) { throw new ArgumentOutOfRangeException(SR.Get(SRID.InvalidConfidence)); diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs index c9f6a03d8e960a..2ef9512dab1a79 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderNLS.cs @@ -50,7 +50,7 @@ internal bool InternalHasFallbackBuffer { get { - return m_fallbackBuffer != null; + return m_fallbackBuffer is not null; } } @@ -58,13 +58,9 @@ internal bool InternalHasFallbackBuffer { get { - if (m_fallbackBuffer == null) - { - if (m_fallback != null) - m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); - else - m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); - } + m_fallbackBuffer ??= m_fallback is not null ? + m_fallback.CreateFallbackBuffer() : + DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); return m_fallbackBuffer; } @@ -72,8 +68,7 @@ internal bool InternalHasFallbackBuffer public override void Reset() { - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) @@ -81,9 +76,11 @@ public override unsafe int GetCharCount(byte[] bytes, int index, int count) 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) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -99,9 +96,11 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count, bo return GetCharCount(pBytes + index, count, flush); } - public override unsafe int GetCharCount(byte* bytes!!, int count, bool flush) + public override unsafe int GetCharCount(byte* bytes, int count, bool flush) { - // Validate parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -119,10 +118,15 @@ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, 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) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -147,10 +151,15 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } - public override unsafe int GetChars(byte* bytes!!, int byteCount, - char* chars!!, int charCount, bool flush) + public override unsafe int GetChars(byte* bytes, int byteCount, + char* chars, int charCount, bool flush) { - // Validate parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -164,11 +173,16 @@ public override unsafe int GetChars(byte* bytes!!, int byteCount, // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) - 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) { - // Validate parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -200,11 +214,16 @@ public override unsafe void Convert(byte[] bytes!!, int byteIndex, int byteCount // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars - public override unsafe void Convert(byte* bytes!!, int byteCount, - char* chars!!, int charCount, bool flush, + public override unsafe void Convert(byte* bytes, int byteCount, + char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { - // Validate input parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -219,7 +238,7 @@ public override unsafe void Convert(byte* bytes!!, int byteCount, // It's completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !HasState) && - (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); + (m_fallbackBuffer is null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs index 974715b9ef8e46..d53150f53152cb 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderNLS.cs @@ -52,7 +52,7 @@ internal bool InternalHasFallbackBuffer { get { - return m_fallbackBuffer != null; + return m_fallbackBuffer is not null; } } @@ -60,13 +60,9 @@ internal bool InternalHasFallbackBuffer { get { - if (m_fallbackBuffer == null) - { - if (m_fallback != null) - m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); - else - m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); - } + m_fallbackBuffer ??= m_fallback is not null ? + m_fallback.CreateFallbackBuffer() : + EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); return m_fallbackBuffer; } @@ -75,13 +71,14 @@ internal bool InternalHasFallbackBuffer public override void Reset() { charLeftOver = (char)0; - if (m_fallbackBuffer != null) - m_fallbackBuffer.Reset(); + m_fallbackBuffer?.Reset(); } - 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) { - // Validate input parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -101,9 +98,11 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count, bo return result; } - public override unsafe int GetByteCount(char* chars!!, int count, bool flush) + public override unsafe int GetByteCount(char* chars, int count, bool flush) { - // Validate input parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -112,10 +111,15 @@ public override unsafe int GetByteCount(char* chars!!, int count, bool flush) return m_encoding.GetByteCount(chars, count, this); } - 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) { - // Validate parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -139,9 +143,14 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } - public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush) + public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { - // Validate parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -152,11 +161,16 @@ public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) - 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) { - // Validate parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -188,11 +202,16 @@ public override unsafe void Convert(char[] chars!!, int charIndex, int charCount // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes - 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) { - // Validate input parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -207,7 +226,7 @@ public override unsafe void Convert(char* chars!!, int charCount, // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (charsUsed == charCount) && (!flush || !HasState) && - (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); + (m_fallbackBuffer is null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs index 6bb8b41dbe3708..6109e97a436fb8 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs @@ -45,9 +45,11 @@ protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec) // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe - public override unsafe int GetByteCount(char[] chars!!, int index, int count) + public override unsafe int GetByteCount(char[] chars, int index, int count) { - // Validate input parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -66,17 +68,22 @@ public override unsafe int GetByteCount(char[] chars!!, int index, int count) // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe - public override unsafe int GetByteCount(string s!!) + public override unsafe int GetByteCount(string s) { + if (s is null) + throw new ArgumentNullException(nameof(s)); + fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. - public override unsafe int GetByteCount(char* chars!!, int count) + public override unsafe int GetByteCount(char* chars, int count) { - // Validate Parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -88,9 +95,15 @@ public override unsafe int GetByteCount(char* chars!!, int count) // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. - 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) { + if (s is null) + throw new ArgumentNullException(nameof(s)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -124,10 +137,15 @@ public override unsafe int GetBytes(string s!!, int charIndex, int charCount, // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe - 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) { - // Validate parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -157,9 +175,14 @@ public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. - public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount) + public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { - // Validate Parameters + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -172,9 +195,11 @@ public override unsafe int GetBytes(char* chars!!, int charCount, byte* bytes!!, // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe - public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) + public override unsafe int GetCharCount(byte[] bytes, int index, int count) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -192,9 +217,11 @@ public override unsafe int GetCharCount(byte[] bytes!!, int index, int count) // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. - public override unsafe int GetCharCount(byte* bytes!!, int count) + public override unsafe int GetCharCount(byte* bytes, int count) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -204,10 +231,15 @@ public override unsafe int GetCharCount(byte* bytes!!, int count) // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe - 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) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -237,9 +269,14 @@ public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. - public unsafe override int GetChars(byte* bytes!!, int byteCount, char* chars!!, int charCount) + public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + + if (chars is null) + throw new ArgumentNullException(nameof(chars)); + if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -252,9 +289,11 @@ public unsafe override int GetChars(byte* bytes!!, int byteCount, char* chars!!, // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. // parent method is safe - public override unsafe string GetString(byte[] bytes!!, int index, int count) + public override unsafe string GetString(byte[] bytes, int index, int count) { - // Validate Parameters + if (bytes is null) + throw new ArgumentNullException(nameof(bytes)); + if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -280,9 +319,9 @@ public override Encoder GetEncoder() internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) { - if (encoder == null || encoder.m_throwOnOverflow || nothingEncoded) + if (encoder is null || encoder.m_throwOnOverflow || nothingEncoded) { - if (encoder != null && encoder.InternalHasFallbackBuffer) + if (encoder is not null && encoder.InternalHasFallbackBuffer) encoder.FallbackBuffer.Reset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken // This happens if user has implemented an encoder fallback with a broken GetMaxCharCount @@ -295,9 +334,9 @@ internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) internal void ThrowCharsOverflow(DecoderNLS? decoder, bool nothingDecoded) { - if (decoder == null || decoder.m_throwOnOverflow || nothingDecoded) + if (decoder is null || decoder.m_throwOnOverflow || nothingDecoded) { - if (decoder != null && decoder.InternalHasFallbackBuffer) + if (decoder is not null && decoder.InternalHasFallbackBuffer) decoder.FallbackBuffer.Reset(); // Special message to include fallback type in case fallback's GetMaxCharCount is broken @@ -329,10 +368,10 @@ public override string EncodingName { get { - if (_encodingName == null) + if (_encodingName is null) { _encodingName = GetLocalizedEncodingNameResource(CodePage); - if (_encodingName == null) + if (_encodingName is null) { throw new NotSupportedException( SR.Format(SR.MissingEncodingNameResource, WebName, CodePage)); @@ -345,7 +384,7 @@ public override string EncodingName // we specifically need to do something reasonable in this case. This currently // returns the English name of the encoding from a static data table. _encodingName = EncodingTable.GetEnglishNameFromCodePage(CodePage); - if (_encodingName == null) + if (_encodingName is null) { throw new NotSupportedException( SR.Format(SR.MissingEncodingNameResource, WebName, CodePage)); @@ -508,10 +547,10 @@ public override string WebName { get { - if (_webName == null) + if (_webName is null) { _webName = EncodingTable.GetWebNameFromCodePage(CodePage); - if (_webName == null) + if (_webName is null) { throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); } diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultHtmlEncoder.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultHtmlEncoder.cs index c3faf767ee5db1..5ab8c388d1bc17 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultHtmlEncoder.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultHtmlEncoder.cs @@ -14,8 +14,13 @@ internal sealed class DefaultHtmlEncoder : HtmlEncoder private readonly OptimizedInboxTextEncoder _innerEncoder; - internal DefaultHtmlEncoder(TextEncoderSettings settings!!) + internal DefaultHtmlEncoder(TextEncoderSettings settings) { + if (settings is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.settings); + } + _innerEncoder = new OptimizedInboxTextEncoder(EscaperImplementation.Singleton, settings.GetAllowedCodePointsBitmap()); } diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultJavaScriptEncoder.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultJavaScriptEncoder.cs index e7a003ddb38da2..be6d2499feb3c0 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultJavaScriptEncoder.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultJavaScriptEncoder.cs @@ -18,8 +18,13 @@ internal DefaultJavaScriptEncoder(TextEncoderSettings settings) { } - private DefaultJavaScriptEncoder(TextEncoderSettings settings!!, bool allowMinimalJsonEscaping) + private DefaultJavaScriptEncoder(TextEncoderSettings settings, bool allowMinimalJsonEscaping) { + if (settings is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.settings); + } + // '\' (U+005C REVERSE SOLIDUS) must always be escaped in Javascript / ECMAScript / JSON. // '/' (U+002F SOLIDUS) is not Javascript / ECMAScript / JSON-sensitive so doesn't need to be escaped. // '`' (U+0060 GRAVE ACCENT) is ECMAScript-sensitive (see ECMA-262). diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultUrlEncoder.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultUrlEncoder.cs index 671ec2f80fb472..6b72c982582b7f 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultUrlEncoder.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/DefaultUrlEncoder.cs @@ -12,8 +12,13 @@ internal sealed class DefaultUrlEncoder : UrlEncoder private readonly OptimizedInboxTextEncoder _innerEncoder; - internal DefaultUrlEncoder(TextEncoderSettings settings!!) + internal DefaultUrlEncoder(TextEncoderSettings settings) { + if (settings is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.settings); + } + // Per RFC 3987, Sec. 2.2, we want encodings that are safe for // four particular components: 'isegment', 'ipath-noscheme', // 'iquery', and 'ifragment'. The relevant definitions are below. diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoder.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoder.cs index 6791980fefcd55..d08ed6ac033804 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoder.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoder.cs @@ -126,8 +126,13 @@ private bool TryEncodeUnicodeScalarUtf8(uint unicodeScalar, Span utf16Scra /// /// String to encode. /// Encoded string. - public virtual string Encode(string value!!) + public virtual string Encode(string value) { + if (value is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + } + int indexOfFirstCharToEncode = FindFirstCharacterToEncode(value.AsSpan()); if (indexOfFirstCharToEncode < 0) { @@ -196,8 +201,17 @@ public void Encode(TextWriter output, string value) /// String whose substring is to be encoded. /// The index where the substring starts. /// Number of characters in the substring. - public virtual void Encode(TextWriter output!!, string value!!, int startIndex, int characterCount) + public virtual void Encode(TextWriter output, string value, int startIndex, int characterCount) { + if (output is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); + } + if (value is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + } + ValidateRanges(startIndex, characterCount, actualInputLength: value.Length); int indexOfFirstCharToEncode = FindFirstCharacterToEncode(value.AsSpan(startIndex, characterCount)); @@ -222,8 +236,17 @@ public virtual void Encode(TextWriter output!!, string value!!, int startIndex, /// Array of characters to be encoded. /// The index where the substring starts. /// Number of characters in the substring. - public virtual void Encode(TextWriter output!!, char[] value!!, int startIndex, int characterCount) + public virtual void Encode(TextWriter output, char[] value, int startIndex, int characterCount) { + if (output is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.output); + } + if (value is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); + } + ValidateRanges(startIndex, characterCount, actualInputLength: value.Length); int indexOfFirstCharToEncode = FindFirstCharacterToEncode(value.AsSpan(startIndex, characterCount)); diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoderSettings.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoderSettings.cs index e2013826b7b2c6..b5b25f5a0c1f53 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoderSettings.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/TextEncoderSettings.cs @@ -24,8 +24,13 @@ public TextEncoderSettings() /// /// Instantiates the filter by cloning the allow list of another . /// - public TextEncoderSettings(TextEncoderSettings other!!) + public TextEncoderSettings(TextEncoderSettings other) { + if (other is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other); + } + _allowedCodePointsBitmap = other.GetAllowedCodePointsBitmap(); // copy byval } @@ -33,8 +38,13 @@ public TextEncoderSettings(TextEncoderSettings other!!) /// Instantiates the filter where only the character ranges specified by /// are allowed by the filter. /// - public TextEncoderSettings(params UnicodeRange[] allowedRanges!!) + public TextEncoderSettings(params UnicodeRange[] allowedRanges) { + if (allowedRanges is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.allowedRanges); + } + AllowRanges(allowedRanges); } @@ -49,8 +59,13 @@ public virtual void AllowCharacter(char character) /// /// Allows all characters specified by through the filter. /// - public virtual void AllowCharacters(params char[] characters!!) + public virtual void AllowCharacters(params char[] characters) { + if (characters is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.characters); + } + for (int i = 0; i < characters.Length; i++) { _allowedCodePointsBitmap.AllowChar(characters[i]); @@ -60,8 +75,13 @@ public virtual void AllowCharacters(params char[] characters!!) /// /// Allows all code points specified by . /// - public virtual void AllowCodePoints(IEnumerable codePoints!!) + public virtual void AllowCodePoints(IEnumerable codePoints) { + if (codePoints is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.codePoints); + } + foreach (var allowedCodePoint in codePoints) { // If the code point can't be represented as a BMP character, skip it. @@ -75,8 +95,13 @@ public virtual void AllowCodePoints(IEnumerable codePoints!!) /// /// Allows all characters specified by through the filter. /// - public virtual void AllowRange(UnicodeRange range!!) + public virtual void AllowRange(UnicodeRange range) { + if (range is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.range); + } + int firstCodePoint = range.FirstCodePoint; int rangeSize = range.Length; for (int i = 0; i < rangeSize; i++) @@ -90,8 +115,13 @@ public virtual void AllowRange(UnicodeRange range!!) /// /// Allows all characters specified by through the filter. /// - public virtual void AllowRanges(params UnicodeRange[] ranges!!) + public virtual void AllowRanges(params UnicodeRange[] ranges) { + if (ranges is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ranges); + } + for (int i = 0; i < ranges.Length; i++) { AllowRange(ranges[i]); @@ -117,8 +147,13 @@ public virtual void ForbidCharacter(char character) /// /// Disallows all characters specified by through the filter. /// - public virtual void ForbidCharacters(params char[] characters!!) + public virtual void ForbidCharacters(params char[] characters) { + if (characters is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.characters); + } + for (int i = 0; i < characters.Length; i++) { _allowedCodePointsBitmap.ForbidChar(characters[i]); @@ -128,8 +163,13 @@ public virtual void ForbidCharacters(params char[] characters!!) /// /// Disallows all characters specified by through the filter. /// - public virtual void ForbidRange(UnicodeRange range!!) + public virtual void ForbidRange(UnicodeRange range) { + if (range is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.range); + } + int firstCodePoint = range.FirstCodePoint; int rangeSize = range.Length; for (int i = 0; i < rangeSize; i++) @@ -143,8 +183,13 @@ public virtual void ForbidRange(UnicodeRange range!!) /// /// Disallows all characters specified by through the filter. /// - public virtual void ForbidRanges(params UnicodeRange[] ranges!!) + public virtual void ForbidRanges(params UnicodeRange[] ranges) { + if (ranges is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ranges); + } + for (int i = 0; i < ranges.Length; i++) { ForbidRange(ranges[i]); diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/ThrowHelper.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/ThrowHelper.cs index 63316b30a3ef5f..d4491ead88d2c4 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/ThrowHelper.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/ThrowHelper.cs @@ -8,6 +8,12 @@ namespace System.Text.Encodings.Web { internal static class ThrowHelper { + [DoesNotReturn] + internal static void ThrowArgumentNullException(ExceptionArgument argument) + { + throw new ArgumentNullException(GetArgumentName(argument)); + } + [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { @@ -26,5 +32,13 @@ private static string GetArgumentName(ExceptionArgument argument) internal enum ExceptionArgument { value, + settings, + output, + other, + allowedRanges, + characters, + codePoints, + range, + ranges, } } diff --git a/src/libraries/System.Text.Json/gen/Reflection/ReflectionExtensions.cs b/src/libraries/System.Text.Json/gen/Reflection/ReflectionExtensions.cs index 73890e15d851c3..1755fabf879136 100644 --- a/src/libraries/System.Text.Json/gen/Reflection/ReflectionExtensions.cs +++ b/src/libraries/System.Text.Json/gen/Reflection/ReflectionExtensions.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -21,8 +21,13 @@ public static TValue GetConstructorArgument(this CustomAttributeData cus return index < customAttributeData.ConstructorArguments.Count ? (TValue)customAttributeData.ConstructorArguments[index].Value! : default!; } - public static bool IsInitOnly(this MethodInfo method!!) + public static bool IsInitOnly(this MethodInfo method) { + if (method is null) + { + throw new ArgumentNullException(nameof(method)); + } + MethodInfoWrapper methodInfoWrapper = (MethodInfoWrapper)method; return methodInfoWrapper.IsInitOnly; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs index 2a06c78204e9f5..5c1ce2061c1c73 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.Parse.cs @@ -115,8 +115,13 @@ public static JsonDocument Parse(ReadOnlySequence utf8Json, JsonDocumentOp /// /// contains unsupported options. /// - public static JsonDocument Parse(Stream utf8Json!!, JsonDocumentOptions options = default) + public static JsonDocument Parse(Stream utf8Json, JsonDocumentOptions options = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + ArraySegment drained = ReadToEnd(utf8Json); Debug.Assert(drained.Array != null); try @@ -191,10 +196,15 @@ internal static JsonDocument ParseValue(string json, JsonDocumentOptions options /// contains unsupported options. /// public static Task ParseAsync( - Stream utf8Json!!, + Stream utf8Json, JsonDocumentOptions options = default, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + return ParseAsyncCore(utf8Json, options, cancellationToken); } @@ -301,8 +311,13 @@ internal static JsonDocument ParseValue(ReadOnlyMemory json, JsonDocumentO /// /// contains unsupported options. /// - public static JsonDocument Parse([StringSyntax(StringSyntaxAttribute.Json)] string json!!, JsonDocumentOptions options = default) + public static JsonDocument Parse([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonDocumentOptions options = default) { + if (json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(json)); + } + return Parse(json.AsMemory(), options); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs index 91351c459a5c6b..1359a09eda75a3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs @@ -103,8 +103,13 @@ public void Dispose() /// /// The parent has been disposed. /// - public void WriteTo(Utf8JsonWriter writer!!) + public void WriteTo(Utf8JsonWriter writer) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + RootElement.WriteTo(writer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs index c4a4613203e5b9..77732b69548d6e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs @@ -111,8 +111,13 @@ public int GetArrayLength() /// /// The parent has been disposed. /// - public JsonElement GetProperty(string propertyName!!) + public JsonElement GetProperty(string propertyName) { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + if (TryGetProperty(propertyName, out JsonElement property)) { return property; @@ -229,8 +234,13 @@ public JsonElement GetProperty(ReadOnlySpan utf8PropertyName) /// The parent has been disposed. /// /// - public bool TryGetProperty(string propertyName!!, out JsonElement value) + public bool TryGetProperty(string propertyName, out JsonElement value) { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + return TryGetProperty(propertyName.AsSpan(), out value); } @@ -1294,8 +1304,13 @@ internal bool TextEqualsHelper(ReadOnlySpan text, bool isPropertyName) /// /// The parent has been disposed. /// - public void WriteTo(Utf8JsonWriter writer!!) + public void WriteTo(Utf8JsonWriter writer) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + CheckValidInstance(); _parent.WriteElementTo(_idx, writer); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs index f22ce88dd6f853..61a66b689ebcbf 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs @@ -110,8 +110,13 @@ internal bool EscapedNameEquals(ReadOnlySpan utf8Text) /// /// The parent has been disposed. /// > - public void WriteTo(Utf8JsonWriter writer!!) + public void WriteTo(Utf8JsonWriter writer) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + writer.WritePropertyName(Name); Value.WriteTo(writer); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs index ca71e316b8f34e..38e530ff3ea34c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonEncodedText.cs @@ -43,8 +43,13 @@ private JsonEncodedText(byte[] utf8Value) /// /// Thrown when the specified value is too large or if it contains invalid UTF-16 characters. /// - public static JsonEncodedText Encode(string value!!, JavaScriptEncoder? encoder = null) + public static JsonEncodedText Encode(string value, JavaScriptEncoder? encoder = null) { + if (value is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(value)); + } + return Encode(value.AsSpan(), encoder); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs index a77087025deec5..8e3180341dba47 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -83,8 +83,13 @@ public void Clear() _propertyDictionary?.Clear(); } - public bool ContainsKey(string propertyName!!) + public bool ContainsKey(string propertyName) { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + return ContainsProperty(propertyName); } @@ -154,8 +159,13 @@ public void CopyTo(KeyValuePair[] array, int index) public ICollection Values => GetValueCollection(); - public bool TryGetValue(string propertyName!!, out T? value) + public bool TryGetValue(string propertyName, out T? value) { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + if (_propertyDictionary != null) { return _propertyDictionary.TryGetValue(propertyName, out value); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs index ba03c8bb9b874c..11f214442712f3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -152,8 +152,13 @@ internal override void GetPath(List path, JsonNode? child) } /// - public override void WriteTo(Utf8JsonWriter writer!!, JsonSerializerOptions? options = null) + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + if (_jsonElement.HasValue) { _jsonElement.Value.WriteTo(writer); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs index 4087ec2323f863..d8eb3657541ccd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.Parse.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; @@ -66,10 +66,15 @@ public abstract partial class JsonNode /// does not represent a valid single JSON value. /// public static JsonNode? Parse( - [StringSyntax(StringSyntaxAttribute.Json)] string json!!, + [StringSyntax(StringSyntaxAttribute.Json)] string json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) { + if (json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(json)); + } + JsonElement element = JsonElement.ParseValue(json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); } @@ -109,10 +114,15 @@ public abstract partial class JsonNode /// does not represent a valid single JSON value. /// public static JsonNode? Parse( - Stream utf8Json!!, + Stream utf8Json, JsonNodeOptions? nodeOptions = null, JsonDocumentOptions documentOptions = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs index 99ceb26c35c8d8..131389b4d1e144 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -113,8 +113,13 @@ public int Count /// /// is . /// - public bool Remove(string propertyName!!) + public bool Remove(string propertyName) { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + InitializeIfRequired(); Debug.Assert(_dictionary != null); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs index b380950c3fda87..4681944426d721 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -82,8 +82,13 @@ public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) => ((IDictionary)this).TryGetValue(propertyName, out jsonNode); /// - public override void WriteTo(Utf8JsonWriter writer!!, JsonSerializerOptions? options = null) + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + if (_jsonElement.HasValue) { // Write the element without converting to nodes. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs index 3a2407c68f5354..18700433da605d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValue.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -61,8 +61,13 @@ private protected JsonValue(JsonNodeOptions? options = null) : base(options) { } /// The that will be used to serialize the value. /// Options to control the behavior. /// The new instance of the class that contains the specified value. - public static JsonValue? Create(T? value, JsonTypeInfo jsonTypeInfo!!, JsonNodeOptions? options = null) + public static JsonValue? Create(T? value, JsonTypeInfo jsonTypeInfo, JsonNodeOptions? options = null) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + if (value == null) { return null; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueNotTrimmable.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueNotTrimmable.cs index 45084fefdc59ce..203ffd7466ab6a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueNotTrimmable.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueNotTrimmable.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; @@ -15,8 +15,13 @@ public JsonValueNotTrimmable(TValue value, JsonNodeOptions? options = null) : ba [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The ctor is marked with RequiresUnreferencedCode.")] - public override void WriteTo(Utf8JsonWriter writer!!, JsonSerializerOptions? options = null) + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + JsonSerializer.Serialize(writer, _value, options); } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueTrimmable.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueTrimmable.cs index 13759e456d045f..32d6fea5407acb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueTrimmable.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueTrimmable.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -25,8 +25,13 @@ public JsonValueTrimmable(TValue value, JsonConverter converter, JsonNod _converter = converter; } - public override void WriteTo(Utf8JsonWriter writer!!, JsonSerializerOptions? options = null) + public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + if (_converter != null) { options ??= JsonSerializerOptions.Default; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs index 1d916fbba80f7a..fb37d18818b381 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConfigurationList.cs @@ -52,8 +52,13 @@ public TItem this[int index] public bool IsReadOnly => false; - public void Add(TItem item!!) + public void Add(TItem item) { + if (item is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(item)); + } + _options.VerifyMutable(); _list.Add(item); OnElementAdded?.Invoke(item); @@ -85,8 +90,13 @@ public int IndexOf(TItem item) return _list.IndexOf(item); } - public void Insert(int index, TItem item!!) + public void Insert(int index, TItem item) { + if (item is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(item)); + } + _options.VerifyMutable(); _list.Insert(index, item); OnElementAdded?.Invoke(item); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs index be523775c64f7c..b597c4d16da6ae 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonMetadataServicesConverter.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -43,8 +43,13 @@ internal JsonConverter Converter internal override bool CanHaveMetadata => Converter.CanHaveMetadata; - public JsonMetadataServicesConverter(Func> converterCreator!!, ConverterStrategy converterStrategy) + public JsonMetadataServicesConverter(Func> converterCreator, ConverterStrategy converterStrategy) { + if (converterCreator is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(converterCreator)); + } + _converterCreator = converterCreator; _converterStrategy = converterStrategy; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs index 898ed9a03041f9..69287a57279e31 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonResumableConverterOfT.cs @@ -10,8 +10,13 @@ namespace System.Text.Json.Serialization /// internal abstract class JsonResumableConverter : JsonConverter { - public sealed override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options!!) + public sealed override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(options)); + } + // Bridge from resumable to value converters. ReadStack state = default; @@ -20,8 +25,13 @@ internal abstract class JsonResumableConverter : JsonConverter return value; } - public sealed override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options!!) + public sealed override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(options)); + } + // Bridge from resumable to value converters. WriteStack state = default; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs index cdd3c1e3089a25..b6afa9185b16ae 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Document.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; @@ -27,8 +27,13 @@ public static partial class JsonSerializer /// for or its serializable members. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static TValue? Deserialize(this JsonDocument document!!, JsonSerializerOptions? options = null) + public static TValue? Deserialize(this JsonDocument document, JsonSerializerOptions? options = null) { + if (document is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(document)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadDocument(document, jsonTypeInfo); } @@ -51,8 +56,17 @@ public static partial class JsonSerializer /// for or its serializable members. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize(this JsonDocument document!!, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerOptions? options = null) { + if (document is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(document)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadDocument(document, jsonTypeInfo); } @@ -78,8 +92,17 @@ public static partial class JsonSerializer /// There is no compatible /// for or its serializable members. /// - public static TValue? Deserialize(this JsonDocument document!!, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize(this JsonDocument document, JsonTypeInfo jsonTypeInfo) { + if (document is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(document)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadDocument(document, jsonTypeInfo); } @@ -119,8 +142,21 @@ public static partial class JsonSerializer /// The method of the provided /// returns for the type to convert. /// - public static object? Deserialize(this JsonDocument document!!, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize(this JsonDocument document, Type returnType, JsonSerializerContext context) { + if (document is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(document)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadDocument(document, jsonTypeInfo); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs index ab22f813b59b49..5b03983f726885 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Element.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; @@ -48,8 +48,13 @@ public static partial class JsonSerializer /// for or its serializable members. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize(this JsonElement element, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerOptions? options = null) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadUsingMetadata(element, jsonTypeInfo); } @@ -71,8 +76,13 @@ public static partial class JsonSerializer /// There is no compatible /// for or its serializable members. /// - public static TValue? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize(this JsonElement element, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadUsingMetadata(element, jsonTypeInfo); } @@ -108,8 +118,17 @@ public static partial class JsonSerializer /// The method of the provided /// returns for the type to convert. /// - public static object? Deserialize(this JsonElement element, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize(this JsonElement element, Type returnType, JsonSerializerContext context) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadUsingMetadata(element, jsonTypeInfo); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs index 68710d4595ce45..e15dcf7c32b0c3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Node.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -47,8 +47,13 @@ public static partial class JsonSerializer /// for or its serializable members. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize(this JsonNode? node, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerOptions? options = null) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadNode(node, jsonTypeInfo); } @@ -70,8 +75,13 @@ public static partial class JsonSerializer /// There is no compatible /// for or its serializable members. /// - public static TValue? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize(this JsonNode? node, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadNode(node, jsonTypeInfo); } @@ -107,8 +117,17 @@ public static partial class JsonSerializer /// The method of the provided /// returns for the type to convert. /// - public static object? Deserialize(this JsonNode? node, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize(this JsonNode? node, Type returnType, JsonSerializerContext context) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadNode(node, jsonTypeInfo); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs index 741603854eb0e4..414b9033001768 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Span.cs @@ -52,8 +52,13 @@ public static partial class JsonSerializer /// for or its serializable members. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType, JsonSerializerOptions? options = null) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpan(utf8Json, jsonTypeInfo); } @@ -74,8 +79,13 @@ public static partial class JsonSerializer /// There is no compatible /// for or its serializable members. /// - public static TValue? Deserialize(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize(ReadOnlySpan utf8Json, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadFromSpan(utf8Json, jsonTypeInfo); } @@ -102,8 +112,17 @@ public static partial class JsonSerializer /// The method on the provided /// did not return a compatible for . /// - public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize(ReadOnlySpan utf8Json, Type returnType, JsonSerializerContext context) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + return ReadFromSpan(utf8Json, GetTypeInfo(context, returnType)); } } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs index 2cc572f03e3481..ae5ba364afd47e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs @@ -42,10 +42,15 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask DeserializeAsync( - Stream utf8Json!!, + Stream utf8Json, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadAllAsync(utf8Json, jsonTypeInfo, cancellationToken); } @@ -72,9 +77,14 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static TValue? Deserialize( - Stream utf8Json!!, + Stream utf8Json, JsonSerializerOptions? options = null) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + return ReadAllUsingOptions(utf8Json, typeof(TValue), options); } @@ -103,11 +113,20 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask DeserializeAsync( - Stream utf8Json!!, - Type returnType!!, + Stream utf8Json, + Type returnType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAllAsync(utf8Json, jsonTypeInfo, cancellationToken); } @@ -134,10 +153,19 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static object? Deserialize( - Stream utf8Json!!, - Type returnType!!, + Stream utf8Json, + Type returnType, JsonSerializerOptions? options = null) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + return ReadAllUsingOptions(utf8Json, returnType, options); } @@ -165,10 +193,19 @@ public static partial class JsonSerializer /// for or its serializable members. /// public static ValueTask DeserializeAsync( - Stream utf8Json!!, - JsonTypeInfo jsonTypeInfo!!, + Stream utf8Json, + JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadAllAsync(utf8Json, jsonTypeInfo, cancellationToken); } @@ -193,9 +230,18 @@ public static partial class JsonSerializer /// for or its serializable members. /// public static TValue? Deserialize( - Stream utf8Json!!, - JsonTypeInfo jsonTypeInfo!!) + Stream utf8Json, + JsonTypeInfo jsonTypeInfo) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadAll(utf8Json, jsonTypeInfo); } @@ -227,11 +273,24 @@ public static partial class JsonSerializer /// did not return a compatible for . /// public static ValueTask DeserializeAsync( - Stream utf8Json!!, - Type returnType!!, - JsonSerializerContext context!!, + Stream utf8Json, + Type returnType, + JsonSerializerContext context, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + return ReadAllAsync(utf8Json, GetTypeInfo(context, returnType), cancellationToken); } @@ -260,10 +319,23 @@ public static partial class JsonSerializer /// did not return a compatible for . /// public static object? Deserialize( - Stream utf8Json!!, - Type returnType!!, - JsonSerializerContext context!!) + Stream utf8Json, + Type returnType, + JsonSerializerContext context) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + return ReadAll(utf8Json, GetTypeInfo(context, returnType)); } @@ -282,10 +354,15 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static IAsyncEnumerable DeserializeAsyncEnumerable( - Stream utf8Json!!, + Stream utf8Json, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + options ??= JsonSerializerOptions.Default; if (!options.IsInitializedForReflectionSerializer) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs index bc8d2ad0ada80d..4aff8fae0f0202 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.String.cs @@ -42,8 +42,13 @@ public static partial class JsonSerializer /// UTF-8 methods since the implementation natively uses UTF-8. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json!!, JsonSerializerOptions? options = null) + public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonSerializerOptions? options = null) { + if (json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(json)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadFromSpan(json.AsSpan(), jsonTypeInfo); } @@ -109,8 +114,17 @@ public static partial class JsonSerializer /// UTF-8 methods since the implementation natively uses UTF-8. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json!!, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, Type returnType, JsonSerializerOptions? options = null) { + if (json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(json)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpan(json.AsSpan(), jsonTypeInfo)!; } @@ -143,8 +157,13 @@ public static partial class JsonSerializer /// UTF-8 methods since the implementation natively uses UTF-8. /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, Type returnType, JsonSerializerOptions? options = null) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + // default/null span is treated as empty JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); @@ -182,8 +201,17 @@ public static partial class JsonSerializer /// Using a is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// - public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json!!, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, JsonTypeInfo jsonTypeInfo) { + if (json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(json)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadFromSpan(json.AsSpan(), jsonTypeInfo); } @@ -218,8 +246,13 @@ public static partial class JsonSerializer /// Using a is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// - public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return ReadFromSpan(json, jsonTypeInfo); } @@ -258,8 +291,21 @@ public static partial class JsonSerializer /// Using a is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// - public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json!!, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] string json, Type returnType, JsonSerializerContext context) { + if (json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(json)); + } + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpan(json.AsSpan(), jsonTypeInfo); } @@ -299,8 +345,17 @@ public static partial class JsonSerializer /// Using a is not as efficient as using the /// UTF-8 methods since the implementation natively uses UTF-8. /// - public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize([StringSyntax(StringSyntaxAttribute.Json)] ReadOnlySpan json, Type returnType, JsonSerializerContext context) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpan(json, jsonTypeInfo); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs index 0a8921ff2fd717..5e5697cde4605b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Utf8JsonReader.cs @@ -107,8 +107,13 @@ public static partial class JsonSerializer /// /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] - public static object? Deserialize(ref Utf8JsonReader reader, Type returnType!!, JsonSerializerOptions? options = null) + public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerOptions? options = null) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return Read(ref reader, jsonTypeInfo); } @@ -156,8 +161,13 @@ public static partial class JsonSerializer /// Hence, , , and are used while reading. /// /// - public static TValue? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo!!) + public static TValue? Deserialize(ref Utf8JsonReader reader, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return Read(ref reader, jsonTypeInfo); } @@ -210,8 +220,17 @@ public static partial class JsonSerializer /// Hence, , , and are used while reading. /// /// - public static object? Deserialize(ref Utf8JsonReader reader, Type returnType!!, JsonSerializerContext context!!) + public static object? Deserialize(ref Utf8JsonReader reader, Type returnType, JsonSerializerContext context) { + if (returnType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(returnType)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + return Read(ref reader, GetTypeInfo(context, returnType)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs index aa280ec24cf166..532a00349b3cfe 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.ByteArray.cs @@ -70,8 +70,13 @@ public static byte[] SerializeToUtf8Bytes( /// /// is . /// - public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo jsonTypeInfo!!) + public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return WriteBytesUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -96,8 +101,13 @@ public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo method of the provided /// returns for the type to convert. /// - public static byte[] SerializeToUtf8Bytes(object? value, Type inputType, JsonSerializerContext context!!) + public static byte[] SerializeToUtf8Bytes(object? value, Type inputType, JsonSerializerContext context) { + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, runtimeType); return WriteBytesUsingGeneratedSerializer(value!, jsonTypeInfo); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs index cbf552e87bb186..2be92327890a4f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Document.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -68,8 +68,13 @@ public static JsonDocument SerializeToDocument(object? value, Type inputType, Js /// /// is . /// - public static JsonDocument SerializeToDocument(TValue value, JsonTypeInfo jsonTypeInfo!!) + public static JsonDocument SerializeToDocument(TValue value, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return WriteDocumentUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -91,8 +96,13 @@ public static JsonDocument SerializeToDocument(TValue value, JsonTypeInf /// /// or is . /// - public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerContext context!!) + public static JsonDocument SerializeToDocument(object? value, Type inputType, JsonSerializerContext context) { + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); return WriteDocumentUsingGeneratedSerializer(value, GetTypeInfo(context, runtimeType)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs index b70d18a46cc40a..0aeb8bbf84b451 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Element.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -68,8 +68,13 @@ public static JsonElement SerializeToElement(object? value, Type inputType, Json /// /// is . /// - public static JsonElement SerializeToElement(TValue value, JsonTypeInfo jsonTypeInfo!!) + public static JsonElement SerializeToElement(TValue value, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return WriteElementUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -91,8 +96,13 @@ public static JsonElement SerializeToElement(TValue value, JsonTypeInfo< /// /// or is . /// - public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerContext context!!) + public static JsonElement SerializeToElement(object? value, Type inputType, JsonSerializerContext context) { + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type type = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo typeInfo = GetTypeInfo(context, type); return WriteElementUsingGeneratedSerializer(value, typeInfo); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Helpers.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Helpers.cs index 535b91cb292274..e9d3932df45f35 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Helpers.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Helpers.cs @@ -97,8 +97,13 @@ private static Type GetRuntimeType(in TValue value) return type; } - private static Type GetRuntimeTypeAndValidateInputType(object? value, Type inputType!!) + private static Type GetRuntimeTypeAndValidateInputType(object? value, Type inputType) { + if (inputType is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(inputType)); + } + if (value is not null) { Type runtimeType = value.GetType(); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs index 4592c3bcdacab7..2360c4618794ff 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Node.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; @@ -69,8 +69,13 @@ public static partial class JsonSerializer /// /// is . /// - public static JsonNode? SerializeToNode(TValue value, JsonTypeInfo jsonTypeInfo!!) + public static JsonNode? SerializeToNode(TValue value, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return WriteNodeUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -92,8 +97,13 @@ public static partial class JsonSerializer /// /// or is . /// - public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerContext context!!) + public static JsonNode? SerializeToNode(object? value, Type inputType, JsonSerializerContext context) { + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, runtimeType); return WriteNodeUsingGeneratedSerializer(value, jsonTypeInfo); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs index 2adcbf5b8dbd27..3ddc473800d09e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs @@ -39,11 +39,16 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static Task SerializeAsync( - Stream utf8Json!!, + Stream utf8Json, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + Type runtimeType = GetRuntimeType(value); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); return WriteStreamAsync(utf8Json, value!, jsonTypeInfo, cancellationToken); @@ -65,10 +70,15 @@ public static Task SerializeAsync( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Stream utf8Json!!, + Stream utf8Json, TValue value, JsonSerializerOptions? options = null) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + Type runtimeType = GetRuntimeType(value); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteStream(utf8Json, value!, jsonTypeInfo); @@ -95,12 +105,17 @@ public static void Serialize( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static Task SerializeAsync( - Stream utf8Json!!, + Stream utf8Json, object? value, Type inputType, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); return WriteStreamAsync(utf8Json, value!, jsonTypeInfo, cancellationToken); @@ -125,11 +140,16 @@ public static Task SerializeAsync( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Stream utf8Json!!, + Stream utf8Json, object? value, Type inputType, JsonSerializerOptions? options = null) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteStream(utf8Json, value!, jsonTypeInfo); @@ -152,11 +172,20 @@ public static void Serialize( /// for or its serializable members. /// public static Task SerializeAsync( - Stream utf8Json!!, + Stream utf8Json, TValue value, - JsonTypeInfo jsonTypeInfo!!, + JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + return WriteStreamAsync(utf8Json, value, jsonTypeInfo, cancellationToken); } @@ -175,10 +204,19 @@ public static Task SerializeAsync( /// for or its serializable members. /// public static void Serialize( - Stream utf8Json!!, + Stream utf8Json, TValue value, - JsonTypeInfo jsonTypeInfo!!) + JsonTypeInfo jsonTypeInfo) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + WriteStream(utf8Json, value, jsonTypeInfo); } @@ -202,12 +240,21 @@ public static void Serialize( /// for or its serializable members. /// public static Task SerializeAsync( - Stream utf8Json!!, + Stream utf8Json, object? value, Type inputType, - JsonSerializerContext context!!, + JsonSerializerContext context, CancellationToken cancellationToken = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); return WriteStreamAsync( utf8Json, @@ -234,11 +281,20 @@ public static Task SerializeAsync( /// for or its serializable members. /// public static void Serialize( - Stream utf8Json!!, + Stream utf8Json, object? value, Type inputType, - JsonSerializerContext context!!) + JsonSerializerContext context) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); WriteStream(utf8Json, value!, GetTypeInfo(context, runtimeType)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs index 7e24645a4e8c04..a63fb0566251aa 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.String.cs @@ -109,15 +109,25 @@ public static string Serialize(TValue value, JsonTypeInfo jsonTy /// encoding since the implementation internally uses UTF-8. See also /// and . /// - public static string Serialize(object? value, Type inputType, JsonSerializerContext context!!) + public static string Serialize(object? value, Type inputType, JsonSerializerContext context) { + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type type = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, type); return WriteStringUsingGeneratedSerializer(value, jsonTypeInfo); } - private static string WriteStringUsingGeneratedSerializer(in TValue value, JsonTypeInfo jsonTypeInfo!!) + private static string WriteStringUsingGeneratedSerializer(in TValue value, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + JsonSerializerOptions options = jsonTypeInfo.Options; using (var output = new PooledByteBufferWriter(options.DefaultBufferSize)) @@ -131,8 +141,13 @@ private static string WriteStringUsingGeneratedSerializer(in TValue valu } } - private static string WriteStringUsingSerializer(in TValue value, JsonTypeInfo jsonTypeInfo!!) + private static string WriteStringUsingSerializer(in TValue value, JsonTypeInfo jsonTypeInfo) { + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + JsonSerializerOptions options = jsonTypeInfo.Options; using (var output = new PooledByteBufferWriter(options.DefaultBufferSize)) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs index 526969f3c0df56..bdd50066c0e647 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Utf8JsonWriter.cs @@ -25,10 +25,15 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Utf8JsonWriter writer!!, + Utf8JsonWriter writer, TValue value, JsonSerializerOptions? options = null) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + Type runtimeType = GetRuntimeType(value); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteUsingSerializer(writer, value, jsonTypeInfo); @@ -53,11 +58,16 @@ public static void Serialize( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Utf8JsonWriter writer!!, + Utf8JsonWriter writer, object? value, Type inputType, JsonSerializerOptions? options = null) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteUsingSerializer(writer, value, jsonTypeInfo); @@ -77,8 +87,17 @@ public static void Serialize( /// There is no compatible /// for or its serializable members. /// - public static void Serialize(Utf8JsonWriter writer!!, TValue value, JsonTypeInfo jsonTypeInfo!!) + public static void Serialize(Utf8JsonWriter writer, TValue value, JsonTypeInfo jsonTypeInfo) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + if (jsonTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(jsonTypeInfo)); + } + WriteUsingGeneratedSerializer(writer, value, jsonTypeInfo); } @@ -103,8 +122,17 @@ public static void Serialize(Utf8JsonWriter writer!!, TValue value, Json /// The method of the provided /// returns for the type to convert. /// - public static void Serialize(Utf8JsonWriter writer!!, object? value, Type inputType, JsonSerializerContext context!!) + public static void Serialize(Utf8JsonWriter writer, object? value, Type inputType, JsonSerializerContext context) { + if (writer is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(writer)); + } + if (context is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(context)); + } + Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); WriteUsingGeneratedSerializer(writer, value, GetTypeInfo(context, runtimeType)); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs index 829ceeeb09213a..91b7d7433214b4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Converters.cs @@ -212,8 +212,13 @@ internal JsonConverter GetConverterFromMember(Type? parentClassType, Type proper /// for or its serializable members. /// [RequiresUnreferencedCode("Getting a converter for a type may require reflection which depends on unreferenced code.")] - public JsonConverter GetConverter(Type typeToConvert!!) + public JsonConverter GetConverter(Type typeToConvert) { + if (typeToConvert is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(typeToConvert)); + } + RootReflectionSerializerDependencies(); return GetConverterInternal(typeToConvert); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index df114e685663c4..32e3d2b2a29885 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs @@ -84,8 +84,13 @@ public JsonSerializerOptions() /// /// is . /// - public JsonSerializerOptions(JsonSerializerOptions options!!) + public JsonSerializerOptions(JsonSerializerOptions options) { + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(options)); + } + _memberAccessorStrategy = options._memberAccessorStrategy; _dictionaryKeyPolicy = options._dictionaryKeyPolicy; _jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs index ccb09d906eee1d..1b49a98ba987cd 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Collections.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -80,14 +80,21 @@ public static JsonTypeInfo CreateDictionaryInfo CreateImmutableDictionaryInfo( JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, - Func>, TCollection> createRangeFunc!!) + Func>, TCollection> createRangeFunc) where TCollection : IReadOnlyDictionary where TKey : notnull - => new SourceGenJsonTypeInfo( + { + if (createRangeFunc is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(createRangeFunc)); + } + + return new SourceGenJsonTypeInfo( options, collectionInfo, () => new ImmutableDictionaryOfTKeyTValueConverter(), createObjectWithArgs: createRangeFunc); + } /// /// Creates serialization metadata for types assignable to . @@ -144,13 +151,20 @@ public static JsonTypeInfo CreateIReadOnlyDictionaryInfo CreateImmutableEnumerableInfo( JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, - Func, TCollection> createRangeFunc!!) + Func, TCollection> createRangeFunc) where TCollection : IEnumerable - => new SourceGenJsonTypeInfo( + { + if (createRangeFunc is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(createRangeFunc)); + } + + return new SourceGenJsonTypeInfo( options, collectionInfo, () => new ImmutableEnumerableOfTConverter(), createObjectWithArgs: createRangeFunc); + } /// /// Creates serialization metadata for types assignable to . @@ -369,14 +383,21 @@ public static JsonTypeInfo CreateQueueInfo( private static JsonTypeInfo CreateStackOrQueueInfo( JsonSerializerOptions options, JsonCollectionInfoValues collectionInfo, - Action addFunc!!) + Action addFunc) where TCollection : IEnumerable - => new SourceGenJsonTypeInfo( + { + if (addFunc is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(addFunc)); + } + + return new SourceGenJsonTypeInfo( options, collectionInfo, () => new StackOrQueueConverter(), createObjectWithArgs: null, addFunc: addFunc); + } /// /// Creates serialization metadata for types assignable to . diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs index 8bb7c29aec7561..035d4c79e91099 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Nodes; @@ -224,8 +224,15 @@ public static JsonConverter GetUnsupportedTypeConverter() /// The to use for serialization and deserialization. /// A instance that converts values. /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. - public static JsonConverter GetEnumConverter(JsonSerializerOptions options!!) where T : struct, Enum - => new EnumConverter(EnumConverterOptions.AllowNumbers, options); + public static JsonConverter GetEnumConverter(JsonSerializerOptions options) where T : struct, Enum + { + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(options)); + } + + return new EnumConverter(EnumConverterOptions.AllowNumbers, options); + } /// /// Creates a instance that converts values. @@ -234,8 +241,13 @@ public static JsonConverter GetEnumConverter(JsonSerializerOptions options /// Serialization metadata for the underlying nullable type. /// A instance that converts values /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. - public static JsonConverter GetNullableConverter(JsonTypeInfo underlyingTypeInfo!!) where T : struct + public static JsonConverter GetNullableConverter(JsonTypeInfo underlyingTypeInfo) where T : struct { + if (underlyingTypeInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(underlyingTypeInfo)); + } + JsonConverter? underlyingConverter = underlyingTypeInfo.PropertyInfoForTypeInfo?.ConverterBase as JsonConverter; if (underlyingConverter == null) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs index c59a8498253ca3..848e45f23c51f2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; @@ -20,8 +20,17 @@ public static partial class JsonMetadataServices /// Provides serialization metadata about the property or field. /// A instance intialized with the provided metadata. /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. - public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions options!!, JsonPropertyInfoValues propertyInfo!!) + public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions options, JsonPropertyInfoValues propertyInfo) { + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(options)); + } + if (propertyInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyInfo)); + } + Type? declaringType = propertyInfo.DeclaringType; if (declaringType == null) { @@ -69,8 +78,19 @@ public static JsonPropertyInfo CreatePropertyInfo(JsonSerializerOptions optio /// Thrown when or is null. /// A instance representing the class or struct. /// This API is for use by the output of the System.Text.Json source generator and should not be called directly. - public static JsonTypeInfo CreateObjectInfo(JsonSerializerOptions options!!, JsonObjectInfoValues objectInfo!!) where T : notnull - => new SourceGenJsonTypeInfo(options, objectInfo); + public static JsonTypeInfo CreateObjectInfo(JsonSerializerOptions options, JsonObjectInfoValues objectInfo) where T : notnull + { + if (options is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(options)); + } + if (objectInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(objectInfo)); + } + + return new SourceGenJsonTypeInfo(options, objectInfo); + } /// /// Creates metadata for a primitive or a type with a custom converter. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/SourceGenJsonTypeInfoOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/SourceGenJsonTypeInfoOfT.cs index c9e5ea88df3d28..d724c39236fef9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/SourceGenJsonTypeInfoOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/SourceGenJsonTypeInfoOfT.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -48,12 +48,17 @@ public SourceGenJsonTypeInfo(JsonSerializerOptions options, JsonObjectInfoValues /// public SourceGenJsonTypeInfo( JsonSerializerOptions options, - JsonCollectionInfoValues collectionInfo!!, + JsonCollectionInfoValues collectionInfo, Func> converterCreator, object? createObjectWithArgs = null, object? addFunc = null) : base(GetConverter(collectionInfo, converterCreator), options) { + if (collectionInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(collectionInfo)); + } + KeyTypeInfo = collectionInfo.KeyInfo; ElementTypeInfo = collectionInfo.ElementInfo ?? throw new ArgumentNullException(nameof(collectionInfo.ElementInfo)); NumberHandling = collectionInfo.NumberHandling; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs index a164e71c13993d..946295161d945f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs @@ -12,6 +12,12 @@ internal static partial class ThrowHelper // If the exception source is this value, the serializer will re-throw as JsonException. public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable"; + [DoesNotReturn] + public static void ThrowArgumentNullException(string parameterName) + { + throw new ArgumentNullException(parameterName); + } + [DoesNotReturn] public static void ThrowArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs index 7950219bf52cd3..4cc66797f65f26 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Bytes.cs @@ -47,8 +47,14 @@ public void WriteBase64String(JsonEncodedText propertyName, ReadOnlySpan b /// /// The property name is escaped before writing. /// - public void WriteBase64String(string propertyName!!, ReadOnlySpan bytes) - => WriteBase64String(propertyName.AsSpan(), bytes); + public void WriteBase64String(string propertyName, ReadOnlySpan bytes) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteBase64String(propertyName.AsSpan(), bytes); + } /// /// Writes the property name and raw bytes value (as a Base64 encoded JSON string) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs index 7c4631a9bbc0ed..cdd3e8930b14fc 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTime.cs @@ -50,8 +50,14 @@ public void WriteString(JsonEncodedText propertyName, DateTime value) /// Writes the using the round-trippable ('O') , for example: 2017-06-12T05:30:45.7680000. /// The property name is escaped before writing. /// - public void WriteString(string propertyName!!, DateTime value) - => WriteString(propertyName.AsSpan(), value); + public void WriteString(string propertyName, DateTime value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteString(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON string) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs index b001530e27ad47..3251fa4e1c14b1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.DateTimeOffset.cs @@ -49,8 +49,14 @@ public void WriteString(JsonEncodedText propertyName, DateTimeOffset value) /// Writes the using the round-trippable ('O') , for example: 2017-06-12T05:30:45.7680000-07:00. /// The property name is escaped before writing. /// - public void WriteString(string propertyName!!, DateTimeOffset value) - => WriteString(propertyName.AsSpan(), value); + public void WriteString(string propertyName, DateTimeOffset value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteString(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON string) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs index 945d33269a2ed5..f90ad0ab5abd69 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Decimal.cs @@ -49,8 +49,14 @@ public void WriteNumber(JsonEncodedText propertyName, decimal value) /// Writes the using the default (that is, 'G'). /// The property name is escaped before writing. /// - public void WriteNumber(string propertyName!!, decimal value) - => WriteNumber(propertyName.AsSpan(), value); + public void WriteNumber(string propertyName, decimal value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs index 7b9e52a4e9c8fb..71e0f57993674f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Double.cs @@ -51,8 +51,14 @@ public void WriteNumber(JsonEncodedText propertyName, double value) /// Writes the using the default (that is, 'G'). /// The property name is escaped before writing. /// - public void WriteNumber(string propertyName!!, double value) - => WriteNumber(propertyName.AsSpan(), value); + public void WriteNumber(string propertyName, double value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs index 8c6d3a8a1aafc3..b6b952daa835da 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Float.cs @@ -51,8 +51,14 @@ public void WriteNumber(JsonEncodedText propertyName, float value) /// Writes the using the default (that is, 'G'). /// The property name is escaped before writing. /// - public void WriteNumber(string propertyName!!, float value) - => WriteNumber(propertyName.AsSpan(), value); + public void WriteNumber(string propertyName, float value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs index a45c0d123350cb..9178873dd2fa06 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Guid.cs @@ -49,8 +49,14 @@ public void WriteString(JsonEncodedText propertyName, Guid value) /// Writes the using the default (that is, 'D'), as the form: nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn. /// The property name is escaped before writing. /// - public void WriteString(string propertyName!!, Guid value) - => WriteString(propertyName.AsSpan(), value); + public void WriteString(string propertyName, Guid value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteString(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON string) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs index 5295155a6fd43d..7a68bc6512cfb7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.Literal.cs @@ -71,8 +71,14 @@ private void WriteLiteralHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpa /// /// The property name is escaped before writing. /// - public void WriteNull(string propertyName!!) - => WriteNull(propertyName.AsSpan()); + public void WriteNull(string propertyName) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNull(propertyName.AsSpan()); + } /// /// Writes the property name and the JSON literal "null" as part of a name/value pair of a JSON object. @@ -163,8 +169,14 @@ public void WriteBoolean(JsonEncodedText propertyName, bool value) /// /// The property name is escaped before writing. /// - public void WriteBoolean(string propertyName!!, bool value) - => WriteBoolean(propertyName.AsSpan(), value); + public void WriteBoolean(string propertyName, bool value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteBoolean(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON literal "true" or "false") as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs index 83550997f97a9a..b7dfaaa8411e79 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.SignedNumber.cs @@ -49,8 +49,14 @@ public void WriteNumber(JsonEncodedText propertyName, long value) /// Writes the using the default (that is, 'G'), for example: 32767. /// The property name is escaped before writing. /// - public void WriteNumber(string propertyName!!, long value) - => WriteNumber(propertyName.AsSpan(), value); + public void WriteNumber(string propertyName, long value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. @@ -134,8 +140,14 @@ public void WriteNumber(JsonEncodedText propertyName, int value) /// Writes the using the default (that is, 'G'), for example: 32767. /// The property name is escaped before writing. /// - public void WriteNumber(string propertyName!!, int value) - => WriteNumber(propertyName.AsSpan(), (long)value); + public void WriteNumber(string propertyName, int value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), (long)value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs index d1fd030cde4fb2..50b6fd38ef7c53 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.String.cs @@ -65,8 +65,14 @@ private void WritePropertyNameHelper(ReadOnlySpan utf8PropertyName) /// /// The property name is escaped before writing. /// - public void WritePropertyName(string propertyName!!) - => WritePropertyName(propertyName.AsSpan()); + public void WritePropertyName(string propertyName) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WritePropertyName(propertyName.AsSpan()); + } /// /// Writes the property name (as a JSON string) as the first part of a name/value pair of a JSON object. @@ -452,8 +458,14 @@ private void WriteStringHelper(ReadOnlySpan utf8PropertyName, ReadOnlySpan /// /// The property name is escaped before writing. /// - public void WriteString(string propertyName!!, JsonEncodedText value) - => WriteString(propertyName.AsSpan(), value); + public void WriteString(string propertyName, JsonEncodedText value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteString(propertyName.AsSpan(), value); + } /// /// Writes the property name and string text value (as a JSON string) as part of a name/value pair of a JSON object. @@ -478,8 +490,13 @@ public void WriteString(string propertyName!!, JsonEncodedText value) /// as if were called. /// /// - public void WriteString(string propertyName!!, string? value) + public void WriteString(string propertyName, string? value) { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + if (value == null) { WriteNull(propertyName.AsSpan()); @@ -627,8 +644,14 @@ private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, R /// /// The property name and value is escaped before writing. /// - public void WriteString(string propertyName!!, ReadOnlySpan value) - => WriteString(propertyName.AsSpan(), value); + public void WriteString(string propertyName, ReadOnlySpan value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteString(propertyName.AsSpan(), value); + } /// /// Writes the UTF-8 property name and text value (as a JSON string) as part of a name/value pair of a JSON object. @@ -711,8 +734,14 @@ private void WriteStringHelperEscapeValue(ReadOnlySpan utf8PropertyName, R /// /// The property name and value is escaped before writing. /// - public void WriteString(string propertyName!!, ReadOnlySpan utf8Value) - => WriteString(propertyName.AsSpan(), utf8Value); + public void WriteString(string propertyName, ReadOnlySpan utf8Value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteString(propertyName.AsSpan(), utf8Value); + } /// /// Writes the property name and UTF-8 text value (as a JSON string) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs index bbf9728518cd25..d256de5517e617 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteProperties.UnsignedNumber.cs @@ -51,8 +51,14 @@ public void WriteNumber(JsonEncodedText propertyName, ulong value) /// The property name is escaped before writing. /// [CLSCompliant(false)] - public void WriteNumber(string propertyName!!, ulong value) - => WriteNumber(propertyName.AsSpan(), value); + public void WriteNumber(string propertyName, ulong value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. @@ -140,8 +146,14 @@ public void WriteNumber(JsonEncodedText propertyName, uint value) /// The property name is escaped before writing. /// [CLSCompliant(false)] - public void WriteNumber(string propertyName!!, uint value) - => WriteNumber(propertyName.AsSpan(), (ulong)value); + public void WriteNumber(string propertyName, uint value) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteNumber(propertyName.AsSpan(), (ulong)value); + } /// /// Writes the property name and value (as a JSON number) as part of a name/value pair of a JSON object. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs index 3cac73e64cd36a..69acd56e933167 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Comment.cs @@ -25,8 +25,14 @@ public sealed partial class Utf8JsonWriter /// /// The comment value is not escaped before writing. /// - public void WriteCommentValue(string value!!) - => WriteCommentValue(value.AsSpan()); + public void WriteCommentValue(string value) + { + if (value is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(value)); + } + WriteCommentValue(value.AsSpan()); + } /// /// Writes the text value (as a JSON comment). diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs index b6a11e72c8b811..c5b2eebd542116 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs @@ -99,8 +99,13 @@ public sealed partial class Utf8JsonWriter : IDisposable, IAsyncDisposable /// /// Thrown when the instance of that is passed in is null. /// - public Utf8JsonWriter(IBufferWriter bufferWriter!!, JsonWriterOptions options = default) + public Utf8JsonWriter(IBufferWriter bufferWriter, JsonWriterOptions options = default) { + if (bufferWriter is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(bufferWriter)); + } + _output = bufferWriter; _options = options; @@ -120,8 +125,13 @@ public Utf8JsonWriter(IBufferWriter bufferWriter!!, JsonWriterOptions opti /// /// Thrown when the instance of that is passed in is null. /// - public Utf8JsonWriter(Stream utf8Json!!, JsonWriterOptions options = default) + public Utf8JsonWriter(Stream utf8Json, JsonWriterOptions options = default) { + if (utf8Json is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(utf8Json)); + } + if (!utf8Json.CanWrite) throw new ArgumentException(SR.StreamNotWritable); @@ -704,8 +714,14 @@ private void WriteStartEscapeProperty(ReadOnlySpan utf8PropertyName, byte /// Thrown when the depth of the JSON has exceeded the maximum depth of 1000 /// OR if this would result in invalid JSON being written (while validation is enabled). /// - public void WriteStartArray(string propertyName!!) - => WriteStartArray(propertyName.AsSpan()); + public void WriteStartArray(string propertyName) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteStartArray(propertyName.AsSpan()); + } /// /// Writes the beginning of a JSON object with a property name as the key. @@ -724,8 +740,14 @@ public void WriteStartArray(string propertyName!!) /// Thrown when the depth of the JSON has exceeded the maximum depth of 1000 /// OR if this would result in invalid JSON being written (while validation is enabled). /// - public void WriteStartObject(string propertyName!!) - => WriteStartObject(propertyName.AsSpan()); + public void WriteStartObject(string propertyName) + { + if (propertyName is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(propertyName)); + } + WriteStartObject(propertyName.AsSpan()); + } /// /// Writes the beginning of a JSON array with a property name as the key. diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/JsonSerializerWrapper.SourceGen.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/JsonSerializerWrapper.SourceGen.cs index 9d02871c9dc620..1ff38417028617 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/JsonSerializerWrapper.SourceGen.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/JsonSerializerWrapper.SourceGen.cs @@ -1,4 +1,4 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -14,10 +14,10 @@ internal sealed class StringSerializerWrapper : JsonSerializerWrapper private readonly JsonSerializerContext _defaultContext; private readonly Func _customContextCreator; - public StringSerializerWrapper(JsonSerializerContext defaultContext!!, Func customContextCreator!!) + public StringSerializerWrapper(JsonSerializerContext defaultContext, Func customContextCreator) { - _defaultContext = defaultContext; - _customContextCreator = customContextCreator; + _defaultContext = defaultContext ?? throw new ArgumentNullException(nameof(defaultContext)); + _customContextCreator = customContextCreator ?? throw new ArgumentNullException(nameof(customContextCreator)); } public override Task SerializeWrapper(object value, Type type, JsonSerializerOptions? options = null) @@ -86,10 +86,10 @@ internal sealed class AsyncStreamSerializerWrapper : StreamingJsonSerializerWrap public override bool IsAsyncSerializer => true; - public AsyncStreamSerializerWrapper(JsonSerializerContext defaultContext!!, Func customContextCreator!!) + public AsyncStreamSerializerWrapper(JsonSerializerContext defaultContext, Func customContextCreator) { - _defaultContext = defaultContext; - _customContextCreator = customContextCreator; + _defaultContext = defaultContext ?? throw new ArgumentNullException(nameof(defaultContext)); + _customContextCreator = customContextCreator ?? throw new ArgumentNullException(nameof(customContextCreator)); } public override async Task DeserializeWrapper(Stream utf8Json, JsonSerializerOptions? options = null) diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.DictionaryInt32StringKeyValueConverter.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.DictionaryInt32StringKeyValueConverter.cs index 7b00d0a4f9380c..58980dbe5b0c7c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.DictionaryInt32StringKeyValueConverter.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/CustomConverterTests/CustomConverterTests.DictionaryInt32StringKeyValueConverter.cs @@ -17,7 +17,7 @@ internal class DictionaryInt32StringKeyValueConverter : JsonConverter> _intToStringConverter; - public DictionaryInt32StringKeyValueConverter(JsonSerializerOptions options!!) + public DictionaryInt32StringKeyValueConverter(JsonSerializerOptions options) { if (options == null) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CollectionDebuggerProxy.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CollectionDebuggerProxy.cs index 78eb4be6400c24..0857edf2ed398a 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CollectionDebuggerProxy.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CollectionDebuggerProxy.cs @@ -10,8 +10,11 @@ internal sealed class CollectionDebuggerProxy { private readonly ICollection _collection; - public CollectionDebuggerProxy(ICollection collection!!) => + public CollectionDebuggerProxy(ICollection collection) + { + ArgumentNullException.ThrowIfNull(collection); _collection = collection; + } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items diff --git a/src/libraries/System.Threading.AccessControl/src/System/Threading/EventWaitHandleAcl.cs b/src/libraries/System.Threading.AccessControl/src/System/Threading/EventWaitHandleAcl.cs index 675b417ef043b8..cf275d68f24a1b 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/EventWaitHandleAcl.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/EventWaitHandleAcl.cs @@ -124,8 +124,10 @@ public static EventWaitHandle OpenExisting(string name, EventWaitHandleRights ri public static bool TryOpenExisting(string name, EventWaitHandleRights rights, [NotNullWhen(returnValue: true)] out EventWaitHandle? result) => OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success; - private static OpenExistingResult OpenExistingWorker(string name!!, EventWaitHandleRights rights, out EventWaitHandle? result) + private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle? result) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); diff --git a/src/libraries/System.Threading.AccessControl/src/System/Threading/MutexAcl.cs b/src/libraries/System.Threading.AccessControl/src/System/Threading/MutexAcl.cs index 87c14e40ad237c..5f671ceac7c98c 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/MutexAcl.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/MutexAcl.cs @@ -115,8 +115,10 @@ public static Mutex OpenExisting(string name, MutexRights rights) public static bool TryOpenExisting(string name, MutexRights rights, [NotNullWhen(returnValue: true)] out Mutex? result) => OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success; - private static OpenExistingResult OpenExistingWorker(string name!!, MutexRights rights, out Mutex? result) + private static OpenExistingResult OpenExistingWorker(string name, MutexRights rights, out Mutex? result) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); diff --git a/src/libraries/System.Threading.AccessControl/src/System/Threading/SemaphoreAcl.cs b/src/libraries/System.Threading.AccessControl/src/System/Threading/SemaphoreAcl.cs index 35ee2c48942c57..c689e2f784e868 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/SemaphoreAcl.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/SemaphoreAcl.cs @@ -128,8 +128,10 @@ public static Semaphore OpenExisting(string name, SemaphoreRights rights) public static bool TryOpenExisting(string name, SemaphoreRights rights, [NotNullWhen(returnValue: true)] out Semaphore? result) => OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success; - private static OpenExistingResult OpenExistingWorker(string name!!, SemaphoreRights rights, out Semaphore? result) + private static OpenExistingResult OpenExistingWorker(string name, SemaphoreRights rights, out Semaphore? result) { + ArgumentNullException.ThrowIfNull(name); + if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); diff --git a/src/libraries/System.Threading.AccessControl/src/System/Threading/ThreadingAclExtensions.cs b/src/libraries/System.Threading.AccessControl/src/System/Threading/ThreadingAclExtensions.cs index 77c7732162cf63..aadb9b2905d725 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/ThreadingAclExtensions.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/ThreadingAclExtensions.cs @@ -16,8 +16,10 @@ public static EventWaitHandleSecurity GetAccessControl(this EventWaitHandle hand return new EventWaitHandleSecurity(handle.GetSafeWaitHandle(), AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static void SetAccessControl(this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity!!) + public static void SetAccessControl(this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity) { + ArgumentNullException.ThrowIfNull(eventSecurity); + eventSecurity.Persist(handle.GetSafeWaitHandle()); } @@ -26,8 +28,10 @@ public static MutexSecurity GetAccessControl(this Mutex mutex) return new MutexSecurity(mutex.GetSafeWaitHandle(), AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static void SetAccessControl(this Mutex mutex, MutexSecurity mutexSecurity!!) + public static void SetAccessControl(this Mutex mutex, MutexSecurity mutexSecurity) { + ArgumentNullException.ThrowIfNull(mutexSecurity); + mutexSecurity.Persist(mutex.GetSafeWaitHandle()); } @@ -36,8 +40,10 @@ public static SemaphoreSecurity GetAccessControl(this Semaphore semaphore) return new SemaphoreSecurity(semaphore.GetSafeWaitHandle(), AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); } - public static void SetAccessControl(this Semaphore semaphore, SemaphoreSecurity semaphoreSecurity!!) + public static void SetAccessControl(this Semaphore semaphore, SemaphoreSecurity semaphoreSecurity) { + ArgumentNullException.ThrowIfNull(semaphoreSecurity); + semaphoreSecurity.Persist(semaphore.GetSafeWaitHandle()); } } diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs index afad0a2cb6fe46..1e260f4c871a02 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/Channel.cs @@ -15,9 +15,20 @@ public static Channel CreateUnbounded() => /// Specifies the type of data in the channel. /// Options that guide the behavior of the channel. /// The created channel. - public static Channel CreateUnbounded(UnboundedChannelOptions options!!) => - options.SingleReader ? new SingleConsumerUnboundedChannel(!options.AllowSynchronousContinuations) : - (Channel)new UnboundedChannel(!options.AllowSynchronousContinuations); + public static Channel CreateUnbounded(UnboundedChannelOptions options) + { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + + if (options.SingleReader) + { + return new SingleConsumerUnboundedChannel(!options.AllowSynchronousContinuations); + } + + return new UnboundedChannel(!options.AllowSynchronousContinuations); + } /// Creates a channel with the specified maximum capacity. /// Specifies the type of data in the channel. @@ -51,8 +62,13 @@ public static Channel CreateBounded(BoundedChannelOptions options) /// Options that guide the behavior of the channel. /// Delegate that will be called when item is being dropped from channel. See . /// The created channel. - public static Channel CreateBounded(BoundedChannelOptions options!!, Action? itemDropped) + public static Channel CreateBounded(BoundedChannelOptions options, Action? itemDropped) { + if (options is null) + { + throw new ArgumentNullException(nameof(options)); + } + return new BoundedChannel(options.Capacity, options.FullMode, !options.AllowSynchronousContinuations, itemDropped); } } diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs index a733ea04e30b49..15285f087af570 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs @@ -36,9 +36,9 @@ public sealed class ConcurrencyLimiter : RateLimiter /// Initializes the . /// /// Options to specify the behavior of the . - public ConcurrencyLimiter(ConcurrencyLimiterOptions options!!) + public ConcurrencyLimiter(ConcurrencyLimiterOptions options) { - _options = options; + _options = options ?? throw new ArgumentNullException(nameof(options)); _permitCount = _options.PermitLimit; } diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/MetadataName.T.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/MetadataName.T.cs index c39e3639a9011f..acc8f1d58ad742 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/MetadataName.T.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/MetadataName.T.cs @@ -17,9 +17,9 @@ public sealed class MetadataName : IEquatable> /// Constructs a object with the given name. /// /// The name of the object. - public MetadataName(string name!!) + public MetadataName(string name) { - _name = name; + _name = name ?? throw new ArgumentNullException(nameof(name)); } /// diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs index 1dfbe7fde9eb92..66cb51b7974acc 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs @@ -43,9 +43,9 @@ public sealed class TokenBucketRateLimiter : ReplenishingRateLimiter /// Initializes the . /// /// Options to specify the behavior of the . - public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options!!) + public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options) { - _options = options; + _options = options ?? throw new ArgumentNullException(nameof(options)); _tokenCount = options.TokenLimit; _idleSince = _lastReplenishmentTick = Stopwatch.GetTimestamp(); diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs index d59b9e2d821054..c14ce2dc090f7c 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.IAsyncEnumerable.cs @@ -14,13 +14,23 @@ public static partial class DataflowBlock /// The which may be used to cancel the receive operation. /// The created async enumerable. /// The is null (Nothing in Visual Basic). - public static async IAsyncEnumerable ReceiveAllAsync(this IReceivableSourceBlock source!!, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public static IAsyncEnumerable ReceiveAllAsync(this IReceivableSourceBlock source, CancellationToken cancellationToken = default) { - while (await source.OutputAvailableAsync(cancellationToken).ConfigureAwait(false)) + if (source is null) { - while (source.TryReceive(out TOutput? item)) + throw new ArgumentNullException(nameof(source)); + } + + return Core(source, cancellationToken); + + static async IAsyncEnumerable Core(IReceivableSourceBlock source, [EnumeratorCancellation] CancellationToken cancellationToken) + { + while (await source.OutputAvailableAsync(cancellationToken).ConfigureAwait(false)) { - yield return item; + while (source.TryReceive(out TOutput? item)) + { + yield return item; + } } } } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs index f196b8b631c52b..fc86396c4b0f08 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs @@ -31,9 +31,18 @@ public static partial class DataflowBlock /// The is null (Nothing in Visual Basic). /// The is null (Nothing in Visual Basic). public static IDisposable LinkTo( - this ISourceBlock source!!, - ITargetBlock target!!) + this ISourceBlock source, + ITargetBlock target) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + // This method exists purely to pass default DataflowLinkOptions // to increase usability of the "90%" case. return source.LinkTo(target, DataflowLinkOptions.Default); @@ -67,11 +76,28 @@ public static IDisposable LinkTo( /// The is null (Nothing in Visual Basic). /// The is null (Nothing in Visual Basic). public static IDisposable LinkTo( - this ISourceBlock source!!, - ITargetBlock target!!, - DataflowLinkOptions linkOptions!!, - Predicate predicate!!) + this ISourceBlock source, + ITargetBlock target, + DataflowLinkOptions linkOptions, + Predicate predicate) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (linkOptions is null) + { + throw new ArgumentNullException(nameof(linkOptions)); + } + if (predicate is null) + { + throw new ArgumentNullException(nameof(predicate)); + } + // Create the filter, which links to the real target, and then // link the real source to this intermediate filter. var filter = new FilteredLinkPropagator(source, target, predicate); @@ -226,8 +252,13 @@ public DebugView(FilteredLinkPropagator filter) /// which will return immediately and will enable the target to postpone the posted message and later consume it /// after SendAsync returns. /// - public static bool Post(this ITargetBlock target!!, TInput item) + public static bool Post(this ITargetBlock target, TInput item) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + return target.OfferMessage(Common.SingleMessageHeader, item, source: null, consumeToAccept: false) == DataflowMessageStatus.Accepted; } @@ -273,8 +304,13 @@ public static Task SendAsync(this ITargetBlock target, TIn /// /// /// The is null (Nothing in Visual Basic). - public static Task SendAsync(this ITargetBlock target!!, TInput item, CancellationToken cancellationToken) + public static Task SendAsync(this ITargetBlock target, TInput item, CancellationToken cancellationToken) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + // Fast path check for cancellation if (cancellationToken.IsCancellationRequested) return Common.CreateTaskFromCancellation(cancellationToken); @@ -747,8 +783,13 @@ public DebugView(SendAsyncSource source) /// This method does not wait until the source has an item to provide. /// It will return whether or not an element was available. /// - public static bool TryReceive(this IReceivableSourceBlock source!!, [MaybeNullWhen(false)] out TOutput item) + public static bool TryReceive(this IReceivableSourceBlock source, [MaybeNullWhen(false)] out TOutput item) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return source.TryReceive(null, out item); } #endregion @@ -822,8 +863,13 @@ public static Task ReceiveAsync( /// timeout is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than . /// public static Task ReceiveAsync( - this ISourceBlock source!!, TimeSpan timeout, CancellationToken cancellationToken) + this ISourceBlock source, TimeSpan timeout, CancellationToken cancellationToken) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + // Validate arguments if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); @@ -902,8 +948,13 @@ public static TOutput Receive( /// If the source successfully offered an item that was received by this operation, it will be returned, even if a concurrent timeout or cancellation request occurs. /// public static TOutput Receive( - this ISourceBlock source!!, TimeSpan timeout, CancellationToken cancellationToken) + this ISourceBlock source, TimeSpan timeout, CancellationToken cancellationToken) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + // Validate arguments if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); @@ -1377,8 +1428,13 @@ public static Task OutputAvailableAsync(this ISourceBlock public static Task OutputAvailableAsync( - this ISourceBlock source!!, CancellationToken cancellationToken) + this ISourceBlock source, CancellationToken cancellationToken) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + // Fast path for cancellation if (cancellationToken.IsCancellationRequested) return Common.CreateTaskFromCancellation(cancellationToken); @@ -1510,8 +1566,13 @@ void IDataflowBlock.Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + TrySetResult(false); } @@ -1541,8 +1602,17 @@ void IDataflowBlock.Fault(Exception exception!!) /// implementation delegates to the specified source. /// public static IPropagatorBlock Encapsulate( - ITargetBlock target!!, ISourceBlock source!!) + ITargetBlock target, ISourceBlock source) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return new EncapsulatingPropagator(target, source); } @@ -1571,8 +1641,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + _target.Fault(exception); } /// @@ -1729,10 +1804,31 @@ public static Task Choose( /// The is null (Nothing in Visual Basic). /// The is null (Nothing in Visual Basic). public static Task Choose( - ISourceBlock source1!!, Action action1!!, - ISourceBlock source2!!, Action action2!!, - DataflowBlockOptions dataflowBlockOptions!!) + ISourceBlock source1, Action action1, + ISourceBlock source2, Action action2, + DataflowBlockOptions dataflowBlockOptions) { + if (source1 is null) + { + throw new ArgumentNullException(nameof(source1)); + } + if (action1 is null) + { + throw new ArgumentNullException(nameof(action1)); + } + if (source2 is null) + { + throw new ArgumentNullException(nameof(source2)); + } + if (action2 is null) + { + throw new ArgumentNullException(nameof(action2)); + } + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Delegate to the shared implementation return ChooseCore(source1, action1, source2, action2, null, null, dataflowBlockOptions); } @@ -1812,11 +1908,40 @@ public static Task Choose( /// The is null (Nothing in Visual Basic). /// The is null (Nothing in Visual Basic). public static Task Choose( - ISourceBlock source1!!, Action action1!!, - ISourceBlock source2!!, Action action2!!, - ISourceBlock source3!!, Action action3!!, - DataflowBlockOptions dataflowBlockOptions!!) + ISourceBlock source1, Action action1, + ISourceBlock source2, Action action2, + ISourceBlock source3, Action action3, + DataflowBlockOptions dataflowBlockOptions) { + if (source1 is null) + { + throw new ArgumentNullException(nameof(source1)); + } + if (action1 is null) + { + throw new ArgumentNullException(nameof(action1)); + } + if (source2 is null) + { + throw new ArgumentNullException(nameof(source2)); + } + if (action2 is null) + { + throw new ArgumentNullException(nameof(action2)); + } + if (source3 is null) + { + throw new ArgumentNullException(nameof(source3)); + } + if (action3 is null) + { + throw new ArgumentNullException(nameof(action3)); + } + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Delegate to the shared implementation return ChooseCore(source1, action1, source2, action2, source3, action3, dataflowBlockOptions); } @@ -2167,8 +2292,13 @@ void IDataflowBlock.Complete() /// The source to wrap. /// An IObservable{TOutput} that enables observers to be subscribed to the source. /// The is null (Nothing in Visual Basic). - public static IObservable AsObservable(this ISourceBlock source!!) + public static IObservable AsObservable(this ISourceBlock source) { + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + return SourceObservable.From(source); } @@ -2230,8 +2360,13 @@ internal SourceObservable(ISourceBlock source) /// Subscribes the observer to the source. /// the observer to subscribe. /// An IDisposable that may be used to unsubscribe the source. - IDisposable IObservable.Subscribe(IObserver observer!!) + IDisposable IObservable.Subscribe(IObserver observer) { + if (observer is null) + { + throw new ArgumentNullException(nameof(observer)); + } + // Validate arguments Common.ContractAssertMonitorStatus(_SubscriptionLock, held: false); @@ -2533,8 +2668,13 @@ private void NotifyObserversOfCompletion(Exception? targetException = null) /// Specifies the type of input accepted by the target block. /// The target to wrap. /// An observer that wraps the target block. - public static IObserver AsObserver(this ITargetBlock target!!) + public static IObserver AsObserver(this ITargetBlock target) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + return new TargetObserver(target); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs index 4215ae5df957fd..7859d86c47f884 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs @@ -66,8 +66,17 @@ public ActionBlock(Func action, ExecutionDataflowBlockOptions data /// The options with which to configure this . /// The is null (Nothing in Visual Basic). /// The is null (Nothing in Visual Basic). - private ActionBlock(Delegate action!!, ExecutionDataflowBlockOptions dataflowBlockOptions!!) + private ActionBlock(Delegate action, ExecutionDataflowBlockOptions dataflowBlockOptions) { + if (action is null) + { + throw new ArgumentNullException(nameof(action)); + } + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -226,8 +235,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + if (_defaultTarget != null) { _defaultTarget.Complete(exception, dropPendingMessages: true); diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs index 0b33c3175444f7..27fc6ed56e3a65 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs @@ -99,8 +99,13 @@ public BatchBlock(int batchSize, GroupingDataflowBlockOptions dataflowBlockOptio public void Complete() { _target.Complete(exception: null, dropPendingMessages: false, releaseReservedMessages: false); } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + _target.Complete(exception, dropPendingMessages: true, releaseReservedMessages: false); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs index e0b9d4e415ef38..6305989a73493e 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs @@ -154,8 +154,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); @@ -406,8 +411,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); @@ -604,8 +614,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + lock (_sharedResources._incomingLock) { if (!_decliningPermanently && !_sharedResources._decliningPermanently) _sharedResources._exceptionAction(exception); diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs index 9a5a6935d8bd88..d0b0cead273331 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs @@ -62,8 +62,13 @@ public BroadcastBlock(Func? cloningFunction) : /// /// The options with which to configure this . /// The is null (Nothing in Visual Basic). - public BroadcastBlock(Func? cloningFunction, DataflowBlockOptions dataflowBlockOptions!!) + public BroadcastBlock(Func? cloningFunction, DataflowBlockOptions dataflowBlockOptions) { + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -107,8 +112,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } @@ -996,8 +1006,17 @@ private void CompleteBlockOncePossible() } /// - internal IDisposable LinkTo(ITargetBlock target!!, DataflowLinkOptions linkOptions!!) + internal IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (linkOptions is null) + { + throw new ArgumentNullException(nameof(linkOptions)); + } + lock (OutgoingLock) { // If we've completed or completion has at least started, offer the message to this target, diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs index ee6dc68b53ef51..de65579a50df27 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs @@ -43,8 +43,13 @@ public BufferBlock() : /// Initializes the with the specified . /// The options with which to configure this . /// The is null (Nothing in Visual Basic). - public BufferBlock(DataflowBlockOptions dataflowBlockOptions!!) + public BufferBlock(DataflowBlockOptions dataflowBlockOptions) { + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -142,8 +147,13 @@ DataflowMessageStatus ITargetBlock.OfferMessage(DataflowMessageHeader message public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs index 874a34fd5b61ed..a56bcda831d3ca 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs @@ -47,8 +47,13 @@ public JoinBlock() : /// Initializes the . /// The options with which to configure this . /// The is null (Nothing in Visual Basic). - public JoinBlock(GroupingDataflowBlockOptions dataflowBlockOptions!!) + public JoinBlock(GroupingDataflowBlockOptions dataflowBlockOptions) { + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -136,8 +141,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized"); @@ -264,8 +274,13 @@ public JoinBlock() : /// Initializes the . /// The options with which to configure this . /// The is null (Nothing in Visual Basic). - public JoinBlock(GroupingDataflowBlockOptions dataflowBlockOptions!!) + public JoinBlock(GroupingDataflowBlockOptions dataflowBlockOptions) { + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -353,8 +368,13 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized"); @@ -914,8 +934,13 @@ internal override void CompleteCore(Exception? exception, bool dropPendingMessag } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + CompleteCore(exception, dropPendingMessages: true, releaseReservedMessages: false); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs index 443013d7834d69..fb5bbe50bd3b63 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs @@ -88,8 +88,13 @@ public TransformBlock(Func> transform, ExecutionDataflowBl /// The options with which to configure this . /// The and are both null (Nothing in Visual Basic). /// The is null (Nothing in Visual Basic). - private TransformBlock(Func? transformSync, Func>? transformAsync, ExecutionDataflowBlockOptions dataflowBlockOptions!!) + private TransformBlock(Func? transformSync, Func>? transformAsync, ExecutionDataflowBlockOptions dataflowBlockOptions) { + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + if (transformSync == null && transformAsync == null) throw new ArgumentNullException("transform"); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); @@ -328,8 +333,13 @@ private void AsyncCompleteProcessMessageWithTask(Task completed, KeyVal public void Complete() { _target.Complete(exception: null, dropPendingMessages: false); } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + _target.Complete(exception, dropPendingMessages: true); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs index 6cb21afa18e06f..a2cfbef8a31044 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs @@ -567,8 +567,13 @@ private void UpdateBoundingCountWithOutputCount(int count) public void Complete() { _target.Complete(exception: null, dropPendingMessages: false); } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + _target.Complete(exception, dropPendingMessages: true); } diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs index a1b97e5a12c713..dbcc1eb06bd3ed 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs @@ -60,8 +60,13 @@ public WriteOnceBlock(Func? cloningFunction) : /// /// The options with which to configure this . /// The is null (Nothing in Visual Basic). - public WriteOnceBlock(Func? cloningFunction, DataflowBlockOptions dataflowBlockOptions!!) + public WriteOnceBlock(Func? cloningFunction, DataflowBlockOptions dataflowBlockOptions) { + if (dataflowBlockOptions is null) + { + throw new ArgumentNullException(nameof(dataflowBlockOptions)); + } + // Store the option _cloningFunction = cloningFunction; _dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -201,8 +206,13 @@ private void CompleteBlock(IList? exceptions) } /// - void IDataflowBlock.Fault(Exception exception!!) + void IDataflowBlock.Fault(Exception exception) { + if (exception is null) + { + throw new ArgumentNullException(nameof(exception)); + } + CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } @@ -290,8 +300,17 @@ bool IReceivableSourceBlock.TryReceiveAll([NotNullWhen(true)] out IList? i } /// - public IDisposable LinkTo(ITargetBlock target!!, DataflowLinkOptions linkOptions!!) + public IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (linkOptions is null) + { + throw new ArgumentNullException(nameof(linkOptions)); + } + bool hasValue; bool isCompleted; lock (ValueLock) diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs index 65ad286b4c4b1d..1399110f8c37ea 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs @@ -121,8 +121,17 @@ internal SourceCore( } /// - internal IDisposable LinkTo(ITargetBlock target!!, DataflowLinkOptions linkOptions!!) + internal IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + if (linkOptions is null) + { + throw new ArgumentNullException(nameof(linkOptions)); + } + // If the block is already completed, there is not much to do - // we have to propagate completion if that was requested, and // then bail without taking the lock. diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.ForEachAsync.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.ForEachAsync.cs index 1b2b328e0cd6ae..619cd1406168d6 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.ForEachAsync.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.ForEachAsync.cs @@ -15,8 +15,11 @@ public static partial class Parallel /// The exception that is thrown when the argument or argument is null. /// A task that represents the entire for each operation. /// The operation will execute at most operations in parallel. - public static Task ForEachAsync(IEnumerable source!!, Func body!!) + public static Task ForEachAsync(IEnumerable source, Func body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, default(CancellationToken), body); } @@ -28,8 +31,11 @@ public static Task ForEachAsync(IEnumerable source!!, FuncThe exception that is thrown when the argument or argument is null. /// A task that represents the entire for each operation. /// The operation will execute at most operations in parallel. - public static Task ForEachAsync(IEnumerable source!!, CancellationToken cancellationToken, Func body!!) + public static Task ForEachAsync(IEnumerable source, CancellationToken cancellationToken, Func body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, cancellationToken, body); } @@ -40,8 +46,12 @@ public static Task ForEachAsync(IEnumerable source!!, Cancella /// An asynchronous delegate that is invoked once per element in the data source. /// The exception that is thrown when the argument or argument is null. /// A task that represents the entire for each operation. - public static Task ForEachAsync(IEnumerable source!!, ParallelOptions parallelOptions!!, Func body!!) + public static Task ForEachAsync(IEnumerable source, ParallelOptions parallelOptions, Func body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForEachAsync(source, parallelOptions.EffectiveMaxConcurrencyLevel, parallelOptions.EffectiveTaskScheduler, parallelOptions.CancellationToken, body); } @@ -159,8 +169,11 @@ private static Task ForEachAsync(IEnumerable source, int dop, /// The exception that is thrown when the argument or argument is null. /// A task that represents the entire for each operation. /// The operation will execute at most operations in parallel. - public static Task ForEachAsync(IAsyncEnumerable source!!, Func body!!) + public static Task ForEachAsync(IAsyncEnumerable source, Func body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, default(CancellationToken), body); } @@ -172,8 +185,11 @@ public static Task ForEachAsync(IAsyncEnumerable source!!, Fun /// The exception that is thrown when the argument or argument is null. /// A task that represents the entire for each operation. /// The operation will execute at most operations in parallel. - public static Task ForEachAsync(IAsyncEnumerable source!!, CancellationToken cancellationToken, Func body!!) + public static Task ForEachAsync(IAsyncEnumerable source, CancellationToken cancellationToken, Func body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, cancellationToken, body); } @@ -184,8 +200,12 @@ public static Task ForEachAsync(IAsyncEnumerable source!!, Can /// An asynchronous delegate that is invoked once per element in the data source. /// The exception that is thrown when the argument or argument is null. /// A task that represents the entire for each operation. - public static Task ForEachAsync(IAsyncEnumerable source!!, ParallelOptions parallelOptions!!, Func body!!) + public static Task ForEachAsync(IAsyncEnumerable source, ParallelOptions parallelOptions, Func body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForEachAsync(source, parallelOptions.EffectiveMaxConcurrencyLevel, parallelOptions.EffectiveTaskScheduler, parallelOptions.CancellationToken, body); } diff --git a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs index 965c5d4d97638d..f4556bfddcda58 100644 --- a/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs +++ b/src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs @@ -187,8 +187,11 @@ public static void Invoke(params Action[] actions) /// provided operations has completed, regardless of whether completion /// occurs due to normal or exceptional termination. /// - public static void Invoke(ParallelOptions parallelOptions!!, params Action[] actions!!) + public static void Invoke(ParallelOptions parallelOptions, params Action[] actions) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(actions); + // On .NET Framework, we throw an ODE if we're passed a disposed CancellationToken. // Here, CancellationToken.ThrowIfSourceDisposed() is not exposed. // This is benign, because we'll end up throwing ODE when we register @@ -377,8 +380,10 @@ public static void Invoke(ParallelOptions parallelOptions!!, params Action[] act /// The delegate is invoked once for each value in the iteration range: /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int32) as a parameter. /// - public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body!!) + public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body) { + ArgumentNullException.ThrowIfNull(body); + return ForWorker( fromInclusive, toExclusive, s_defaultParallelOptions, @@ -401,8 +406,10 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action< /// The delegate is invoked once for each value in the iteration range: /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int64) as a parameter. /// - public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action body!!) + public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action body) { + ArgumentNullException.ThrowIfNull(body); + return ForWorker64( fromInclusive, toExclusive, s_defaultParallelOptions, body, null, null, null, null); @@ -435,8 +442,11 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Actio /// The delegate is invoked once for each value in the iteration range: /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int32) as a parameter. /// - public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions!!, Action body!!) + public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action body) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForWorker( fromInclusive, toExclusive, parallelOptions, body, null, null, null, null); @@ -469,8 +479,11 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Paralle /// The delegate is invoked once for each value in the iteration range: /// [fromInclusive, toExclusive). It is provided with the iteration count (an Int64) as a parameter. /// - public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions!!, Action body!!) + public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, Action body) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForWorker64( fromInclusive, toExclusive, parallelOptions, body, null, null, null, null); @@ -516,8 +529,10 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Paral /// relevant information about the loop's completion. /// /// - public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body!!) + public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body) { + ArgumentNullException.ThrowIfNull(body); + return ForWorker( fromInclusive, toExclusive, s_defaultParallelOptions, null, body, null, null, null); @@ -541,8 +556,10 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action< /// and a ParallelLoopState instance that may be /// used to break out of the loop prematurely. /// - public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action body!!) + public static ParallelLoopResult For(long fromInclusive, long toExclusive, Action body) { + ArgumentNullException.ThrowIfNull(body); + return ForWorker64( fromInclusive, toExclusive, s_defaultParallelOptions, null, body, null, null, null); @@ -577,8 +594,11 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Actio /// and a ParallelLoopState instance that may be /// used to break out of the loop prematurely. /// - public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions!!, Action body!!) + public static ParallelLoopResult For(int fromInclusive, int toExclusive, ParallelOptions parallelOptions, Action body) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForWorker( fromInclusive, toExclusive, parallelOptions, null, body, null, null, null); @@ -613,9 +633,12 @@ public static ParallelLoopResult For(int fromInclusive, int toExclusive, Paralle /// and a ParallelLoopState instance that may be /// used to break out of the loop prematurely. /// - public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions!!, - Action body!!) + public static ParallelLoopResult For(long fromInclusive, long toExclusive, ParallelOptions parallelOptions, + Action body) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForWorker64( fromInclusive, toExclusive, parallelOptions, null, body, null, null, null); @@ -661,10 +684,14 @@ public static ParallelLoopResult For(long fromInclusive, long toExclusive, Paral /// public static ParallelLoopResult For( int fromInclusive, int toExclusive, - Func localInit!!, - Func body!!, - Action localFinally!!) + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForWorker( fromInclusive, toExclusive, s_defaultParallelOptions, null, null, body, localInit, localFinally); @@ -710,10 +737,14 @@ public static ParallelLoopResult For( /// public static ParallelLoopResult For( long fromInclusive, long toExclusive, - Func localInit!!, - Func body!!, - Action localFinally!!) + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForWorker64( fromInclusive, toExclusive, s_defaultParallelOptions, null, null, body, localInit, localFinally); @@ -769,11 +800,16 @@ public static ParallelLoopResult For( /// /// public static ParallelLoopResult For( - int fromInclusive, int toExclusive, ParallelOptions parallelOptions!!, - Func localInit!!, - Func body!!, - Action localFinally!!) + int fromInclusive, int toExclusive, ParallelOptions parallelOptions, + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForWorker( fromInclusive, toExclusive, parallelOptions, null, null, body, localInit, localFinally); @@ -829,11 +865,16 @@ public static ParallelLoopResult For( /// /// public static ParallelLoopResult For( - long fromInclusive, long toExclusive, ParallelOptions parallelOptions!!, - Func localInit!!, - Func body!!, - Action localFinally!!) + long fromInclusive, long toExclusive, ParallelOptions parallelOptions, + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForWorker64( fromInclusive, toExclusive, parallelOptions, null, null, body, localInit, localFinally); @@ -1412,8 +1453,11 @@ private static ParallelLoopResult ForWorker64( /// The delegate is invoked once for each element in the /// enumerable. It is provided with the current element as a parameter. /// - public static ParallelLoopResult ForEach(IEnumerable source!!, Action body!!) + public static ParallelLoopResult ForEach(IEnumerable source, Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachWorker( source, s_defaultParallelOptions, body, null, null, null, null, null, null); } @@ -1448,8 +1492,12 @@ public static ParallelLoopResult ForEach(IEnumerable source!!, /// The delegate is invoked once for each element in the /// enumerable. It is provided with the current element as a parameter. /// - public static ParallelLoopResult ForEach(IEnumerable source!!, ParallelOptions parallelOptions!!, Action body!!) + public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForEachWorker( source, parallelOptions, body, null, null, null, null, null, null); } @@ -1475,8 +1523,11 @@ public static ParallelLoopResult ForEach(IEnumerable source!!, /// and a ParallelLoopState instance that may be /// used to break out of the loop prematurely. /// - public static ParallelLoopResult ForEach(IEnumerable source!!, Action body!!) + public static ParallelLoopResult ForEach(IEnumerable source, Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachWorker( source, s_defaultParallelOptions, null, body, null, null, null, null, null); } @@ -1513,8 +1564,12 @@ public static ParallelLoopResult ForEach(IEnumerable source!!, /// and a ParallelLoopState instance that may be /// used to break out of the loop prematurely. /// - public static ParallelLoopResult ForEach(IEnumerable source!!, ParallelOptions parallelOptions!!, Action body!!) + public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForEachWorker( source, parallelOptions, null, body, null, null, null, null, null); } @@ -1540,8 +1595,11 @@ public static ParallelLoopResult ForEach(IEnumerable source!!, /// a ParallelLoopState instance that may be /// used to break out of the loop prematurely, and the current element's index (an Int64). /// - public static ParallelLoopResult ForEach(IEnumerable source!!, Action body!!) + public static ParallelLoopResult ForEach(IEnumerable source, Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return ForEachWorker( source, s_defaultParallelOptions, null, null, body, null, null, null, null); } @@ -1578,8 +1636,12 @@ public static ParallelLoopResult ForEach(IEnumerable source!!, /// a ParallelLoopState instance that may be /// used to break out of the loop prematurely, and the current element's index (an Int64). /// - public static ParallelLoopResult ForEach(IEnumerable source!!, ParallelOptions parallelOptions!!, Action body!!) + public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return ForEachWorker( source, parallelOptions, null, null, body, null, null, null, null); } @@ -1625,9 +1687,14 @@ public static ParallelLoopResult ForEach(IEnumerable source!!, /// action on each thread's local state. /// /// - public static ParallelLoopResult ForEach(IEnumerable source!!, Func localInit!!, - Func body!!, Action localFinally!!) + public static ParallelLoopResult ForEach(IEnumerable source, Func localInit, + Func body, Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForEachWorker( source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -1684,10 +1751,16 @@ public static ParallelLoopResult ForEach(IEnumerable s /// action on each thread's local state. /// /// - public static ParallelLoopResult ForEach(IEnumerable source!!, - ParallelOptions parallelOptions!!, Func localInit!!, - Func body!!, Action localFinally!!) + public static ParallelLoopResult ForEach(IEnumerable source, + ParallelOptions parallelOptions, Func localInit, + Func body, Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForEachWorker( source, parallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -1733,9 +1806,14 @@ public static ParallelLoopResult ForEach(IEnumerable s /// action on each thread's local state. /// /// - public static ParallelLoopResult ForEach(IEnumerable source!!, Func localInit!!, - Func body!!, Action localFinally!!) + public static ParallelLoopResult ForEach(IEnumerable source, Func localInit, + Func body, Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForEachWorker( source, s_defaultParallelOptions, null, null, null, null, body, localInit, localFinally); } @@ -1792,9 +1870,15 @@ public static ParallelLoopResult ForEach(IEnumerable s /// action on each thread's local state. /// /// - public static ParallelLoopResult ForEach(IEnumerable source!!, ParallelOptions parallelOptions!!, Func localInit!!, - Func body!!, Action localFinally!!) + public static ParallelLoopResult ForEach(IEnumerable source, ParallelOptions parallelOptions, Func localInit, + Func body, Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return ForEachWorker( source, parallelOptions, null, null, null, null, body, localInit, localFinally); } @@ -2023,9 +2107,12 @@ private static ParallelLoopResult ForEachWorker( /// /// public static ParallelLoopResult ForEach( - Partitioner source!!, - Action body!!) + Partitioner source, + Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return PartitionerForEachWorker(source, s_defaultParallelOptions, body, null, null, null, null, null, null); } @@ -2073,9 +2160,12 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source!!, - Action body!!) + Partitioner source, + Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + return PartitionerForEachWorker(source, s_defaultParallelOptions, null, body, null, null, null, null, null); } @@ -2126,9 +2216,12 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source!!, - Action body!!) + OrderablePartitioner source, + Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(body); + if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); @@ -2199,11 +2292,16 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source!!, - Func localInit!!, - Func body!!, - Action localFinally!!) + Partitioner source, + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return PartitionerForEachWorker(source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -2272,11 +2370,16 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source!!, - Func localInit!!, - Func body!!, - Action localFinally!!) + OrderablePartitioner source, + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); @@ -2338,10 +2441,14 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source!!, - ParallelOptions parallelOptions!!, - Action body!!) + Partitioner source, + ParallelOptions parallelOptions, + Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return PartitionerForEachWorker(source, parallelOptions, body, null, null, null, null, null, null); } @@ -2400,10 +2507,14 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source!!, - ParallelOptions parallelOptions!!, - Action body!!) + Partitioner source, + ParallelOptions parallelOptions, + Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + return PartitionerForEachWorker(source, parallelOptions, null, body, null, null, null, null, null); } @@ -2465,10 +2576,14 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source!!, - ParallelOptions parallelOptions!!, - Action body!!) + OrderablePartitioner source, + ParallelOptions parallelOptions, + Action body) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(body); + if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); @@ -2550,12 +2665,18 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source!!, - ParallelOptions parallelOptions!!, - Func localInit!!, - Func body!!, - Action localFinally!!) + Partitioner source, + ParallelOptions parallelOptions, + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + return PartitionerForEachWorker(source, parallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -2635,12 +2756,18 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source!!, - ParallelOptions parallelOptions!!, - Func localInit!!, - Func body!!, - Action localFinally!!) + OrderablePartitioner source, + ParallelOptions parallelOptions, + Func localInit, + Func body, + Action localFinally) { + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(parallelOptions); + ArgumentNullException.ThrowIfNull(localInit); + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(localFinally); + if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); diff --git a/src/libraries/System.Threading.Tasks/tests/CancellationTokenTests.cs b/src/libraries/System.Threading.Tasks/tests/CancellationTokenTests.cs index 153d0db3d6322a..05131b101ccb6e 100644 --- a/src/libraries/System.Threading.Tasks/tests/CancellationTokenTests.cs +++ b/src/libraries/System.Threading.Tasks/tests/CancellationTokenTests.cs @@ -861,7 +861,7 @@ public static void ODEWhenDisposingLinkedCTS() } else { - Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - Exception Occurred (not an ODE!!): " + ex)); + Assert.True(false, string.Format("Bug901737_ODEWhenDisposingLinkedCTS: - Exception Occurred (not an ODE!): " + ex)); } } } diff --git a/src/libraries/System.Threading/src/System/Threading/Barrier.cs b/src/libraries/System.Threading/src/System/Threading/Barrier.cs index 0e4df8e52b0cb1..61114b240d0c84 100644 --- a/src/libraries/System.Threading/src/System/Threading/Barrier.cs +++ b/src/libraries/System.Threading/src/System/Threading/Barrier.cs @@ -56,7 +56,7 @@ public BarrierPostPhaseException(string? message) /// A string that describes the exception. /// The exception that is the cause of the current exception. public BarrierPostPhaseException(string? message, Exception? innerException) - : base(message == null ? SR.BarrierPostPhaseException : message, innerException) + : base(message is null ? SR.BarrierPostPhaseException : message, innerException) { } @@ -228,7 +228,7 @@ public Barrier(int participantCount, Action? postPhaseAction) _evenEvent = new ManualResetEventSlim(false); // Capture the context if the post phase action is not null - if (postPhaseAction != null) + if (postPhaseAction is not null) { _ownerThreadContext = ExecutionContext.Capture(); } @@ -316,7 +316,6 @@ public long AddParticipant() [UnsupportedOSPlatform("browser")] public long AddParticipants(int participantCount) { - // check dispose ThrowIfDisposed(); if (participantCount < 1) @@ -421,10 +420,8 @@ public void RemoveParticipant() /// disposed. public void RemoveParticipants(int participantCount) { - // check dispose ThrowIfDisposed(); - // Validate input if (participantCount < 1) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, @@ -750,7 +747,7 @@ public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellatio } } - if (_exception != null) + if (_exception is not null) throw new BarrierPostPhaseException(_exception); return true; @@ -764,19 +761,15 @@ public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellatio private void FinishPhase(bool observedSense) { // Execute the PHA in try/finally block to reset the variables back in case of it threw an exception - if (_postPhaseAction != null) + if (_postPhaseAction is not null) { try { // Capture the caller thread ID to check if the Add/RemoveParticipant(s) is called from the PHA _actionCallerID = Environment.CurrentManagedThreadId; - if (_ownerThreadContext != null) + if (_ownerThreadContext is not null) { - ContextCallback? handler = s_invokePostPhaseAction; - if (handler == null) - { - s_invokePostPhaseAction = handler = InvokePostPhaseAction; - } + ContextCallback? handler = s_invokePostPhaseAction ??= InvokePostPhaseAction; ExecutionContext.Run(_ownerThreadContext, handler, this); } else @@ -794,7 +787,7 @@ private void FinishPhase(bool observedSense) { _actionCallerID = 0; SetResetEvents(observedSense); - if (_exception != null) + if (_exception is not null) throw new BarrierPostPhaseException(_exception); } } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs index 5634d5e1097614..7e1ab20be86aa6 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs @@ -22,10 +22,7 @@ public static class TransactionInterop { internal static DistributedTransaction ConvertToDistributedTransaction(Transaction transaction) { - if (null == transaction) - { - throw new ArgumentNullException(nameof(transaction)); - } + ArgumentNullException.ThrowIfNull(transaction); if (transaction.Disposed) { @@ -60,8 +57,11 @@ internal static DistributedTransaction ConvertToDistributedTransaction(Transacti /// public static readonly Guid PromoterTypeDtc = new Guid("14229753-FFE1-428D-82B7-DF73045CB8DA"); - public static byte[] GetExportCookie(Transaction transaction!!, byte[] whereabouts!!) + public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts) { + ArgumentNullException.ThrowIfNull(transaction); + ArgumentNullException.ThrowIfNull(whereabouts); + TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { @@ -83,8 +83,10 @@ public static byte[] GetExportCookie(Transaction transaction!!, byte[] whereabou return cookie; } - public static Transaction GetTransactionFromExportCookie(byte[] cookie!!) + public static Transaction GetTransactionFromExportCookie(byte[] cookie) { + ArgumentNullException.ThrowIfNull(cookie); + if (cookie.Length < 32) { throw new ArgumentException(SR.InvalidArgument, nameof(cookie)); @@ -132,10 +134,7 @@ public static Transaction GetTransactionFromExportCookie(byte[] cookie!!) public static byte[] GetTransmitterPropagationToken(Transaction transaction) { - if (null == transaction) - { - throw new ArgumentNullException(nameof(transaction)); - } + ArgumentNullException.ThrowIfNull(transaction); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) @@ -154,8 +153,10 @@ public static byte[] GetTransmitterPropagationToken(Transaction transaction) return token; } - public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken!!) + public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) { + ArgumentNullException.ThrowIfNull(propagationToken); + if (propagationToken.Length < 24) { throw new ArgumentException(SR.InvalidArgument, nameof(propagationToken)); @@ -198,10 +199,7 @@ public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] p public static IDtcTransaction GetDtcTransaction(Transaction transaction) { - if (null == transaction) - { - throw new ArgumentNullException(nameof(transaction)); - } + ArgumentNullException.ThrowIfNull(transaction); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) @@ -220,8 +218,10 @@ public static IDtcTransaction GetDtcTransaction(Transaction transaction) return transactionNative; } - public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative!!) + public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative) { + ArgumentNullException.ThrowIfNull(transactionNative); + TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { @@ -254,8 +254,10 @@ public static byte[] GetWhereabouts() return returnValue; } - internal static DistributedTransaction GetDistributedTransactionFromTransmitterPropagationToken(byte[] propagationToken!!) + internal static DistributedTransaction GetDistributedTransactionFromTransmitterPropagationToken(byte[] propagationToken) { + ArgumentNullException.ThrowIfNull(propagationToken); + if (propagationToken.Length < 24) { throw new ArgumentException(SR.InvalidArgument, nameof(propagationToken)); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index 3bbca6b204f1ce..c27adcf5842bfd 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -135,15 +135,9 @@ public static Enlistment Reenlist( throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } - if (null == recoveryInformation) - { - throw new ArgumentNullException(nameof(recoveryInformation)); - } + ArgumentNullException.ThrowIfNull(recoveryInformation); - if (null == enlistmentNotification) - { - throw new ArgumentNullException(nameof(enlistmentNotification)); - } + ArgumentNullException.ThrowIfNull(enlistmentNotification); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index 026f9e840212c1..34bc3b898d078f 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -466,10 +466,7 @@ private void Initialize( TimeSpan scopeTimeout, bool interopModeSpecified) { - if (null == transactionToUse) - { - throw new ArgumentNullException(nameof(transactionToUse)); - } + ArgumentNullException.ThrowIfNull(transactionToUse); ValidateScopeTimeout(nameof(scopeTimeout), scopeTimeout); diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs index 6f3f8be18def5f..ddb3a33ebc50f5 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs @@ -80,8 +80,11 @@ public override string ToString() public static NameValueCollection ParseQueryString(string query) => ParseQueryString(query, Encoding.UTF8); - public static NameValueCollection ParseQueryString(string query!!, Encoding encoding!!) + public static NameValueCollection ParseQueryString(string query, Encoding encoding) { + ArgumentNullException.ThrowIfNull(query); + ArgumentNullException.ThrowIfNull(encoding); + HttpQSCollection result = new HttpQSCollection(); int queryLength = query.Length; int namePos = queryLength > 0 && query[0] == '?' ? 1 : 0; diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs index 7aab010e301d7c..e6e90c7b97fb18 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/HttpEncoder.cs @@ -108,16 +108,20 @@ private static void HtmlAttributeEncodeInternal(string s, TextWriter output) [return: NotNullIfNotNull("value")] internal static string? HtmlDecode(string? value) => string.IsNullOrEmpty(value) ? value : WebUtility.HtmlDecode(value); - internal static void HtmlDecode(string? value, TextWriter output!!) + internal static void HtmlDecode(string? value, TextWriter output) { + ArgumentNullException.ThrowIfNull(output); + output.Write(WebUtility.HtmlDecode(value)); } [return: NotNullIfNotNull("value")] internal static string? HtmlEncode(string? value) => string.IsNullOrEmpty(value) ? value : WebUtility.HtmlEncode(value); - internal static void HtmlEncode(string? value, TextWriter output!!) + internal static void HtmlEncode(string? value, TextWriter output) { + ArgumentNullException.ThrowIfNull(output); + output.Write(WebUtility.HtmlEncode(value)); } diff --git a/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Certificate2UI.cs b/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Certificate2UI.cs index a6b90e6f034d2d..7a3cb22e6ebd49 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Certificate2UI.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Certificate2UI.cs @@ -18,13 +18,17 @@ public sealed class X509Certificate2UI internal const int ERROR_SUCCESS = 0; internal const int ERROR_CANCELLED = 1223; - public static void DisplayCertificate(X509Certificate2 certificate!!) + public static void DisplayCertificate(X509Certificate2 certificate) { + ArgumentNullException.ThrowIfNull(certificate); + DisplayX509Certificate(certificate, IntPtr.Zero); } - public static void DisplayCertificate(X509Certificate2 certificate!!, IntPtr hwndParent) + public static void DisplayCertificate(X509Certificate2 certificate, IntPtr hwndParent) { + ArgumentNullException.ThrowIfNull(certificate); + DisplayX509Certificate(certificate, hwndParent); } @@ -83,8 +87,10 @@ private static unsafe void DisplayX509Certificate(X509Certificate2 certificate, } } - private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates!!, string? title, string? message, X509SelectionFlag selectionFlag, IntPtr hwndParent) + private static X509Certificate2Collection SelectFromCollectionHelper(X509Certificate2Collection certificates, string? title, string? message, X509SelectionFlag selectionFlag, IntPtr hwndParent) { + ArgumentNullException.ThrowIfNull(certificates); + if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection) throw new ArgumentException(SR.Format(SR.Enum_InvalidValue, nameof(selectionFlag))); diff --git a/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs index 9bdabb7a9ac943..0160049e614cfb 100644 --- a/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Array.Mono.cs @@ -99,11 +99,8 @@ public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array des public static void Copy(Array sourceArray, Array destinationArray, int length) { - if (sourceArray == null) - throw new ArgumentNullException(nameof(sourceArray)); - - if (destinationArray == null) - throw new ArgumentNullException(nameof(destinationArray)); + ArgumentNullException.ThrowIfNull(sourceArray); + ArgumentNullException.ThrowIfNull(destinationArray); Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length); @@ -116,11 +113,8 @@ public static void Copy(Array sourceArray, int sourceIndex, Array destinationArr private static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable) { - if (sourceArray == null) - throw new ArgumentNullException(nameof(sourceArray)); - - if (destinationArray == null) - throw new ArgumentNullException(nameof(destinationArray)); + ArgumentNullException.ThrowIfNull(sourceArray); + ArgumentNullException.ThrowIfNull(destinationArray); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/mono/System.Private.CoreLib/src/System/Attribute.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Attribute.Mono.cs index 4f9ddf06470fbc..7cdec768c13add 100644 --- a/src/mono/System.Private.CoreLib/src/System/Attribute.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Attribute.Mono.cs @@ -9,8 +9,7 @@ public partial class Attribute { private static Attribute? GetAttr(ICustomAttributeProvider element, Type attributeType, bool inherit) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(attributeType); if (!attributeType.IsSubclassOf(typeof(Attribute)) && !attributeType.IsInterface && attributeType != typeof(Attribute) && attributeType != typeof(CustomAttribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); diff --git a/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs index b8960fa9757730..c0c16a947782f9 100644 --- a/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Delegate.Mono.cs @@ -75,11 +75,8 @@ public partial class Delegate [RequiresUnreferencedCode("The target method might be removed")] protected Delegate(object target, string method) { - if (target is null) - throw new ArgumentNullException(nameof(target)); - - if (method is null) - throw new ArgumentNullException(nameof(method)); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(method); this._target = target; this.data = new DelegateData() @@ -90,14 +87,12 @@ protected Delegate(object target, string method) protected Delegate([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method) { - if (target is null) - throw new ArgumentNullException(nameof(target)); + ArgumentNullException.ThrowIfNull(target); if (target.ContainsGenericParameters) throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target)); - if (method is null) - throw new ArgumentNullException(nameof(method)); + ArgumentNullException.ThrowIfNull(method); if (target is not RuntimeType) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target)); @@ -125,10 +120,8 @@ public static Delegate CreateDelegate(Type type, object? firstArgument, MethodIn private static Delegate? CreateDelegate(Type type, object? firstArgument, MethodInfo method, bool throwOnBindFailure, bool allowClosed) { - if (type is null) - throw new ArgumentNullException(nameof(type)); - if (method is null) - throw new ArgumentNullException(nameof(method)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(method); if (type is not RuntimeType rtType) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); @@ -159,12 +152,9 @@ public static Delegate CreateDelegate(Type type, object? firstArgument, MethodIn [RequiresUnreferencedCode("The target method might be removed")] public static Delegate? CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) { - if (type is null) - throw new ArgumentNullException(nameof(type)); - if (target is null) - throw new ArgumentNullException(nameof(target)); - if (method is null) - throw new ArgumentNullException(nameof(method)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(target); + ArgumentNullException.ThrowIfNull(method); if (type is not RuntimeType rtType) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); @@ -185,14 +175,11 @@ public static Delegate CreateDelegate(Type type, object? firstArgument, MethodIn public static Delegate? CreateDelegate(Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method, bool ignoreCase, bool throwOnBindFailure) { - if (type is null) - throw new ArgumentNullException(nameof(type)); - if (target is null) - throw new ArgumentNullException(nameof(target)); + ArgumentNullException.ThrowIfNull(type); + ArgumentNullException.ThrowIfNull(target); if (target.ContainsGenericParameters) throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target)); - if (method is null) - throw new ArgumentNullException(nameof(method)); + ArgumentNullException.ThrowIfNull(method); if (type is not RuntimeType rtType) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); diff --git a/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs b/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs index 0ca9fc56fa5bb4..c08eec30fbebea 100644 --- a/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/GC.Mono.cs @@ -133,8 +133,7 @@ public static int MaxGeneration public static void SuppressFinalize(object obj) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); _SuppressFinalize(obj); } @@ -143,8 +142,7 @@ public static void SuppressFinalize(object obj) public static void ReRegisterForFinalize(object obj) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); _ReRegisterForFinalize(obj); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs index ca8e66fc9c2eff..ba531f8083f1e8 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Assembly.Mono.cs @@ -16,8 +16,7 @@ public partial class Assembly [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly? LoadWithPartialName(string partialName) { - if (partialName == null) - throw new ArgumentNullException(nameof(partialName)); + ArgumentNullException.ThrowIfNull(partialName); if (partialName.Length == 0 || partialName[0] == '\0') throw new ArgumentException(SR.Format_StringZeroLength, nameof(partialName)); @@ -57,8 +56,7 @@ public static Assembly GetExecutingAssembly() [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(string assemblyString) { - if (assemblyString == null) - throw new ArgumentNullException(nameof(assemblyString)); + ArgumentNullException.ThrowIfNull(assemblyString); var name = new AssemblyName(assemblyString); // TODO: trigger assemblyFromResolveEvent @@ -70,8 +68,7 @@ public static Assembly Load(string assemblyString) [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(AssemblyName assemblyRef) { - if (assemblyRef == null) - throw new ArgumentNullException(nameof(assemblyRef)); + ArgumentNullException.ThrowIfNull(assemblyRef); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return Load(assemblyRef, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs index fc89f24ec66d6d..95d547fd0eeec4 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs @@ -138,10 +138,8 @@ internal static object[] GetCustomAttributesBase(ICustomAttributeProvider obj, T internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type attributeType, bool inherit) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(obj); + ArgumentNullException.ThrowIfNull(attributeType); if (!attributeType.IsSubclassOf(typeof(Attribute)) && !attributeType.IsInterface && attributeType != typeof(Attribute) && attributeType != typeof(CustomAttribute) && attributeType != typeof(object)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); @@ -299,8 +297,7 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, Type internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, bool inherit) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); if (!inherit) return (object[])GetCustomAttributesBase(obj, null, false).Clone(); @@ -316,8 +313,7 @@ internal static object[] GetCustomAttributes(ICustomAttributeProvider obj, bool internal static IList GetCustomAttributesData(ICustomAttributeProvider obj, bool inherit = false) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); if (!inherit) return GetCustomAttributesDataBase(obj, null, false); @@ -327,10 +323,8 @@ internal static IList GetCustomAttributesData(ICustomAttrib internal static IList GetCustomAttributesData(ICustomAttributeProvider obj, Type? attributeType, bool inherit) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(obj); + ArgumentNullException.ThrowIfNull(attributeType); if (attributeType == typeof(CustomAttribute)) attributeType = null; @@ -553,8 +547,7 @@ internal static IList GetCustomAttributesDataBase(ICustomAt internal static bool IsDefined(ICustomAttributeProvider obj, Type attributeType, bool inherit) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(attributeType); if (!attributeType.IsSubclassOf(typeof(Attribute)) && !attributeType.IsInterface && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass + " " + attributeType.FullName); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs index 8ca34db3060968..a6f89d45fcc598 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs @@ -239,8 +239,7 @@ public override bool ReflectionOnly [RequiresDynamicCode("Defining a dynamic assembly requires dynamic code.")] public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { - if (name == null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); return new AssemblyBuilder(name, access); } @@ -286,8 +285,7 @@ public ModuleBuilder DefineDynamicModule(string name) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); if (cattrs != null) { @@ -307,10 +305,8 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); + ArgumentNullException.ThrowIfNull(con); + ArgumentNullException.ThrowIfNull(binaryAttribute); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs index e16d7a0f0f54c0..9779420b53db14 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.Mono.cs @@ -259,8 +259,7 @@ public ILGenerator GetILGenerator(int streamSize) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; if (attrname == "System.Runtime.CompilerServices.MethodImplAttribute") @@ -288,10 +287,8 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); + ArgumentNullException.ThrowIfNull(con); + ArgumentNullException.ThrowIfNull(binaryAttribute); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs index ec4c34d8663252..8458d9cfc89515 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.Mono.cs @@ -79,10 +79,9 @@ internal object Invoke() internal CustomAttributeBuilder(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); + ArgumentNullException.ThrowIfNull(con); + ArgumentNullException.ThrowIfNull(binaryAttribute); + ctor = con; data = (byte[])binaryAttribute.Clone(); /* should we check that the user supplied data is correct? */ @@ -171,18 +170,13 @@ private void Initialize(ConstructorInfo con, object?[] constructorArgs, this.namedFields = namedFields; this.fieldValues = fieldValues; - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (constructorArgs == null) - throw new ArgumentNullException(nameof(constructorArgs)); - if (namedProperties == null) - throw new ArgumentNullException(nameof(namedProperties)); - if (propertyValues == null) - throw new ArgumentNullException(nameof(propertyValues)); - if (namedFields == null) - throw new ArgumentNullException(nameof(namedFields)); - if (fieldValues == null) - throw new ArgumentNullException(nameof(fieldValues)); + ArgumentNullException.ThrowIfNull(con); + ArgumentNullException.ThrowIfNull(constructorArgs); + ArgumentNullException.ThrowIfNull(namedProperties); + ArgumentNullException.ThrowIfNull(propertyValues); + ArgumentNullException.ThrowIfNull(namedFields); + ArgumentNullException.ThrowIfNull(fieldValues); + if (con.GetParametersCount() != constructorArgs.Length) throw new ArgumentException(SR.Argument_BadParameterCountsForConstructor); if (namedProperties.Length != propertyValues.Length) diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs index fc2db5443d0a9f..18ed42f645201a 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILInfo.cs @@ -113,8 +113,8 @@ public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { if (codeSize < 0) throw new ArgumentOutOfRangeException(nameof(codeSize), SR.ArgumentOutOfRange_GenericPositive); - if (codeSize > 0 && code == null) - throw new ArgumentNullException(nameof(code)); + if (codeSize > 0) + ArgumentNullException.ThrowIfNull(code); method.GetILGenerator().SetCode(code, codeSize, maxStackSize); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs index f892fc9f786a8a..ea546a52133862 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -118,14 +118,13 @@ public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, bool [DynamicDependency(nameof(owner))] // Automatically keeps all previous fields too due to StructLayout private DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type? owner, Module? m, bool skipVisibility, bool anonHosted, bool typeOwner) { - if (name == null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); if (returnType == null) returnType = typeof(void); - if (owner == null && typeOwner) - throw new ArgumentNullException(nameof(owner)); - if ((m == null) && !anonHosted) - throw new ArgumentNullException(nameof(m)); + if (typeOwner) + ArgumentNullException.ThrowIfNull(owner); + if (!anonHosted) + ArgumentNullException.ThrowIfNull(m); if (parameterTypes != null) { for (int i = 0; i < parameterTypes.Length; ++i) @@ -194,8 +193,7 @@ private void CreateDynMethod() public sealed override Delegate CreateDelegate(Type delegateType) { - if (delegateType == null) - throw new ArgumentNullException(nameof(delegateType)); + ArgumentNullException.ThrowIfNull(delegateType); if (deleg != null) return deleg; @@ -207,8 +205,7 @@ public sealed override Delegate CreateDelegate(Type delegateType) public sealed override Delegate CreateDelegate(Type delegateType, object? target) { - if (delegateType == null) - throw new ArgumentNullException(nameof(delegateType)); + ArgumentNullException.ThrowIfNull(delegateType); CreateDynMethod(); @@ -243,8 +240,10 @@ public override object[] GetCustomAttributes(bool inherit) return new object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; } - public override object[] GetCustomAttributes(Type attributeType!!, bool inherit) + public override object[] GetCustomAttributes(Type attributeType, bool inherit) { + ArgumentNullException.ThrowIfNull(attributeType); + if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) { // avoid calling CreateInstance() in the common case where the type is Attribute @@ -342,8 +341,7 @@ public override object Invoke (object obj, object[] parameters) { public override bool IsDefined(Type attributeType, bool inherit) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(attributeType); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return true; diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs index 02842003b3aa7b..65fedfb5c6023b 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.Mono.cs @@ -72,8 +72,7 @@ internal int get_next_table_index(int table, int count) public void AddOtherMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); RejectIfCreated(); if (other_methods != null) { @@ -90,30 +89,26 @@ public void AddOtherMethod(MethodBuilder mdBuilder) public void SetAddOnMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); RejectIfCreated(); add_method = mdBuilder; } public void SetRaiseMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); RejectIfCreated(); raise_method = mdBuilder; } public void SetRemoveOnMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); RejectIfCreated(); remove_method = mdBuilder; } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); RejectIfCreated(); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") @@ -137,10 +132,8 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); + ArgumentNullException.ThrowIfNull(con); + ArgumentNullException.ThrowIfNull(binaryAttribute); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs index 1a3ca8518014a1..0ceb6a433e8b47 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.Mono.cs @@ -61,8 +61,7 @@ public sealed partial class FieldBuilder : FieldInfo [DynamicDependency(nameof(modOpt))] // Automatically keeps all previous fields too due to StructLayout internal FieldBuilder(TypeBuilder tb, string fieldName, Type type, FieldAttributes attributes, Type[]? modReq, Type[]? modOpt) { - if (type == null) - throw new ArgumentNullException(nameof(type)); + ArgumentNullException.ThrowIfNull(type); attrs = attributes & ~FieldAttributes.ReservedMask; name = fieldName; @@ -174,8 +173,7 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { RejectIfCreated(); - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; if (attrname == "System.Runtime.InteropServices.FieldOffsetAttribute") diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs index a999b9129f069c..ee5b300de5560a 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -428,8 +428,7 @@ public override MethodBase? DeclaringMethod public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); if (cattrs != null) { diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs index 93f303ed111fab..249e596ef1b2ef 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.Mono.cs @@ -444,8 +444,7 @@ public virtual LocalBuilder DeclareLocal(Type localType) public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { - if (localType == null) - throw new ArgumentNullException(nameof(localType)); + ArgumentNullException.ThrowIfNull(localType); if (localType.IsUserType) throw new NotSupportedException("User defined subclasses of System.Type are not yet supported."); LocalBuilder res = new LocalBuilder(localType, this); @@ -572,8 +571,7 @@ public virtual void Emit(OpCode opcode, Label label) public virtual void Emit(OpCode opcode, Label[] labels) { - if (labels == null) - throw new ArgumentNullException(nameof(labels)); + ArgumentNullException.ThrowIfNull(labels); /* opcode needs to be switch. */ int count = labels.Length; @@ -620,8 +618,7 @@ public virtual void Emit(OpCode opcode, Label[] labels) public virtual void Emit(OpCode opcode, LocalBuilder local) { - if (local == null) - throw new ArgumentNullException(nameof(local)); + ArgumentNullException.ThrowIfNull(local); if (local.ilgen != this) throw new ArgumentException(SR.Argument_UnmatchedMethodForLocal, nameof(local)); @@ -712,8 +709,7 @@ public virtual void Emit(OpCode opcode, LocalBuilder local) public virtual void Emit(OpCode opcode, MethodInfo meth) { - if (meth == null) - throw new ArgumentNullException(nameof(meth)); + ArgumentNullException.ThrowIfNull(meth); // For compatibility with MS if ((meth is DynamicMethod) && ((opcode == OpCodes.Ldftn) || (opcode == OpCodes.Ldvirtftn) || (opcode == OpCodes.Ldtoken))) @@ -785,8 +781,7 @@ public virtual void Emit(OpCode opcode, Type cls) // FIXME: vararg methods are not supported public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes) { - if (methodInfo == null) - throw new ArgumentNullException(nameof(methodInfo)); + ArgumentNullException.ThrowIfNull(methodInfo); short value = opcode.Value; if (!(value == OpCodes.Call.Value || value == OpCodes.Callvirt.Value)) throw new NotSupportedException("Only Call and CallVirt are allowed"); @@ -827,8 +822,7 @@ public virtual void EmitCalli(OpCode opcode, CallingConventions callingConventio public virtual void EmitWriteLine(FieldInfo fld) { - if (fld == null) - throw new ArgumentNullException(nameof(fld)); + ArgumentNullException.ThrowIfNull(fld); // The MS implementation does not check for valuetypes here but it // should. Also, it should check that if the field is not static, @@ -846,8 +840,7 @@ public virtual void EmitWriteLine(FieldInfo fld) public virtual void EmitWriteLine(LocalBuilder localBuilder) { - if (localBuilder == null) - throw new ArgumentNullException(nameof(localBuilder)); + ArgumentNullException.ThrowIfNull(localBuilder); if (localBuilder.LocalType is TypeBuilder) throw new ArgumentException("Output streams do not support TypeBuilders."); // The MS implementation does not check for valuetypes here but it @@ -896,8 +889,7 @@ public virtual void MarkLabel(Label loc) public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type excType) { - if (excType == null) - throw new ArgumentNullException(nameof(excType)); + ArgumentNullException.ThrowIfNull(excType); if (!((excType == typeof(Exception)) || excType.IsSubclassOf(typeof(Exception)))) throw new ArgumentException("Type should be an exception type", nameof(excType)); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs index 5ee9c612b61944..bc40ef548f9e9a 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.Mono.cs @@ -386,8 +386,7 @@ internal void ResolveUserTypes() public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); switch (customBuilder.Ctor.ReflectedType!.FullName) { @@ -475,10 +474,8 @@ public void SetCustomAttribute(CustomAttributeBuilder customBuilder) public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); + ArgumentNullException.ThrowIfNull(con); + ArgumentNullException.ThrowIfNull(binaryAttribute); SetCustomAttribute(new CustomAttributeBuilder(con, binaryAttribute)); } @@ -546,12 +543,10 @@ public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { if (!IsGenericMethodDefinition) throw new InvalidOperationException("Method is not a generic method definition"); - if (typeArguments == null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(typeArguments); foreach (Type type in typeArguments) { - if (type == null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(type, nameof(typeArguments)); } return new MethodOnTypeBuilderInst(this, typeArguments); @@ -595,8 +590,7 @@ public override Type[] GetGenericArguments() public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { - if (names == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(names); if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); type.check_not_created(); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs index b2d0614ad58352..91525190483f11 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/MethodOnTypeBuilderInst.cs @@ -253,16 +253,14 @@ public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) if (!base_method.IsGenericMethodDefinition || (method_arguments != null)) throw new InvalidOperationException("Method is not a generic method definition"); - if (methodInstantiation == null) - throw new ArgumentNullException(nameof(methodInstantiation)); + ArgumentNullException.ThrowIfNull(methodInstantiation); if (base_method.GetGenericArguments().Length != methodInstantiation.Length) throw new ArgumentException("Incorrect length", nameof(methodInstantiation)); foreach (Type type in methodInstantiation) { - if (type == null) - throw new ArgumentNullException(nameof(methodInstantiation)); + ArgumentNullException.ThrowIfNull(type, nameof(methodInstantiation)); } return new MethodOnTypeBuilderInst(this, methodInstantiation); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs index e23cc5999e04a9..5dbafb84175d2f 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs @@ -129,8 +129,7 @@ public void CreateGlobalFunctions() public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { - if (data == null) - throw new ArgumentNullException(nameof(data)); + ArgumentNullException.ThrowIfNull(data); FieldAttributes maskedAttributes = attributes & ~FieldAttributes.ReservedMask; FieldBuilder fb = DefineDataImpl(name, data.Length, maskedAttributes | FieldAttributes.HasFieldRVA); @@ -199,8 +198,7 @@ private void addGlobalMethod(MethodBuilder mb) public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { - if (name == null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException("global methods must be static"); if (global_type_created != null) @@ -215,8 +213,7 @@ public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { - if (name == null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException("global methods must be static"); if (global_type_created != null) @@ -251,8 +248,7 @@ private void AddType(TypeBuilder tb) Justification = "Reflection.Emit is not subject to trimming")] private TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces, PackingSize packingSize, int typesize) { - if (name == null) - throw new ArgumentNullException("fullname"); + ArgumentNullException.ThrowIfNull(name, "fullname"); ITypeIdentifier ident = TypeIdentifiers.FromInternal(name); if (name_cache.ContainsKey(ident)) throw new ArgumentException("Duplicate type name within an assembly."); @@ -437,8 +433,7 @@ internal int get_next_table_index(int table, int count) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); if (cattrs != null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder[cattrs.Length + 1]; @@ -486,8 +481,7 @@ public override Type[] GetTypes() internal static int GetMethodToken(MethodInfo method) { - if (method == null) - throw new ArgumentNullException(nameof(method)); + ArgumentNullException.ThrowIfNull(method); return method.MetadataToken; } @@ -499,16 +493,14 @@ internal int GetArrayMethodToken(Type arrayClass, string methodName, CallingConv internal static int GetConstructorToken(ConstructorInfo con) { - if (con == null) - throw new ArgumentNullException(nameof(con)); + ArgumentNullException.ThrowIfNull(con); return con.MetadataToken; } internal static int GetFieldToken(FieldInfo field) { - if (field == null) - throw new ArgumentNullException(nameof(field)); + ArgumentNullException.ThrowIfNull(field); return field.MetadataToken; } @@ -521,22 +513,19 @@ internal int GetSignatureToken(byte[] sigBytes, int sigLength) internal int GetSignatureToken(SignatureHelper sigHelper) { - if (sigHelper == null) - throw new ArgumentNullException(nameof(sigHelper)); + ArgumentNullException.ThrowIfNull(sigHelper); return GetToken(sigHelper); } internal int GetStringConstant(string str) { - if (str == null) - throw new ArgumentNullException(nameof(str)); + ArgumentNullException.ThrowIfNull(str); return GetToken(str); } internal static int GetTypeToken(Type type) { - if (type == null) - throw new ArgumentNullException(nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (type.IsByRef) throw new ArgumentException("type can't be a byref type", nameof(type)); return type.MetadataToken; diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs index 13fbbcb6c86f12..041784bdce33ee 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.Mono.cs @@ -111,8 +111,7 @@ public override Type ReflectedType public void AddOtherMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); typeb.check_not_created(); } @@ -162,8 +161,7 @@ public void SetConstant(object? defaultValue) public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); typeb.check_not_created(); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; if (attrname == "System.Runtime.CompilerServices.SpecialNameAttribute") @@ -194,15 +192,13 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) public void SetGetMethod(MethodBuilder mdBuilder) { typeb.check_not_created(); - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); get_method = mdBuilder; } public void SetSetMethod(MethodBuilder mdBuilder) { - if (mdBuilder == null) - throw new ArgumentNullException(nameof(mdBuilder)); + ArgumentNullException.ThrowIfNull(mdBuilder); set_method = mdBuilder; } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index 738cde70583531..84a0090801ff0a 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -190,8 +190,7 @@ private static void ValidateParameterModifiers(string name, Type[] parameter_mod { foreach (Type modifier in parameter_modifiers) { - if (modifier == null) - throw new ArgumentNullException(name); + ArgumentNullException.ThrowIfNull(modifier, name); if (modifier.IsArray) throw new ArgumentException("Array type not permitted", name); if (modifier.ContainsGenericParameters) @@ -224,8 +223,7 @@ private static Exception MissingFeature() // FIXME: "Currently we ignore requiredCustomModifiers and optionalCustomModifiers" public void AddArguments(Type[]? arguments, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { - if (arguments == null) - throw new ArgumentNullException(nameof(arguments)); + ArgumentNullException.ThrowIfNull(arguments); // For now if (requiredCustomModifiers != null || optionalCustomModifiers != null) @@ -250,8 +248,7 @@ public void AddArgument(Type argument, bool pinned) public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) { - if (argument == null) - throw new ArgumentNullException(nameof(argument)); + ArgumentNullException.ThrowIfNull(argument); if (requiredCustomModifiers != null) ValidateParameterModifiers("requiredCustomModifiers", requiredCustomModifiers); @@ -267,8 +264,7 @@ public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? public void AddArgument(Type clsArgument) { - if (clsArgument == null) - throw new ArgumentNullException(nameof(clsArgument)); + ArgumentNullException.ThrowIfNull(clsArgument); AppendArray(ref arguments, clsArgument); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs index ca42b91a427e65..b2ee5ca15a30b6 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs @@ -268,8 +268,7 @@ public override Type? ReflectedType public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType) { - if (interfaceType == null) - throw new ArgumentNullException(nameof(interfaceType)); + ArgumentNullException.ThrowIfNull(interfaceType); check_not_created(); @@ -577,10 +576,8 @@ MethodBuilder res public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) { - if (methodInfoBody == null) - throw new ArgumentNullException(nameof(methodInfoBody)); - if (methodInfoDeclaration == null) - throw new ArgumentNullException(nameof(methodInfoDeclaration)); + ArgumentNullException.ThrowIfNull(methodInfoBody); + ArgumentNullException.ThrowIfNull(methodInfoDeclaration); check_not_created(); if (methodInfoBody.DeclaringType != this) throw new ArgumentException("method body must belong to this type"); @@ -1302,16 +1299,14 @@ public override Type MakeGenericType(params Type[] typeArguments) if (!IsGenericTypeDefinition) throw new InvalidOperationException("not a generic type definition"); - if (typeArguments == null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(typeArguments); if (generic_params!.Length != typeArguments.Length) throw new ArgumentException(string.Format("The type or method has {0} generic parameter(s) but {1} generic argument(s) where provided. A generic argument must be provided for each generic parameter.", generic_params.Length, typeArguments.Length), nameof(typeArguments)); foreach (Type t in typeArguments) { - if (t == null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(t, nameof(typeArguments)); } Type[] copy = new Type[typeArguments.Length]; @@ -1335,8 +1330,7 @@ public override RuntimeTypeHandle TypeHandle public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); + ArgumentNullException.ThrowIfNull(customBuilder); string? attrname = customBuilder.Ctor.ReflectedType!.FullName; if (attrname == "System.Runtime.InteropServices.StructLayoutAttribute") @@ -1465,8 +1459,7 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) public EventBuilder DefineEvent(string name, EventAttributes attributes, Type eventtype) { check_name(nameof(name), name); - if (eventtype == null) - throw new ArgumentNullException(nameof(eventtype)); + ArgumentNullException.ThrowIfNull(eventtype); check_not_created(); EventBuilder res = new EventBuilder(this, name, attributes, eventtype); @@ -1487,8 +1480,7 @@ public EventBuilder DefineEvent(string name, EventAttributes attributes, Type ev public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { - if (data == null) - throw new ArgumentNullException(nameof(data)); + ArgumentNullException.ThrowIfNull(data); FieldBuilder res = DefineUninitializedData(name, data.Length, attributes); res.SetRVAData(data); @@ -1717,8 +1709,7 @@ public override MethodBase? DeclaringMethod public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { - if (names == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(names); if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); @@ -1726,8 +1717,8 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam for (int i = 0; i < names.Length; i++) { string item = names[i]; - if (item == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(item, nameof(names)); + generic_params[i] = new GenericTypeParameterBuilder(this, null, item, i); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs index f6882f4984721a..2e71ac31a0f96d 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/MemberInfo.Mono.cs @@ -7,8 +7,7 @@ public abstract partial class MemberInfo { internal bool HasSameMetadataDefinitionAsCore(MemberInfo other) where TOther : MemberInfo { - if (other == null) - throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); // Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it! if (!(other is TOther)) diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs index afac9bf5e88da7..a3c1517ee60274 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs @@ -29,7 +29,7 @@ public static void ApplyUpdate(Assembly assembly, ReadOnlySpan metadataDel { if (assembly is not RuntimeAssembly runtimeAssembly) { - if (assembly is null) throw new ArgumentNullException(nameof(assembly)); + ArgumentNullException.ThrowIfNull(assembly); throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index c1d33f9e061f4d..8b7ce372961b8f 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -135,8 +135,7 @@ public override Module ManifestModule internal static AssemblyName? CreateAssemblyName(string assemblyString, out RuntimeAssembly? assemblyFromResolveEvent) { - if (assemblyString == null) - throw new ArgumentNullException(nameof(assemblyString)); + ArgumentNullException.ThrowIfNull(assemblyString); if ((assemblyString.Length == 0) || (assemblyString[0] == '\0')) @@ -265,8 +264,8 @@ private static void AddPublicNestedTypes(Type type, List types, List candidates = GetPropertyCandidates(name, bindingAttr, types, false); @@ -883,7 +882,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); MemberListType listType; FilterHelper(bindingAttr, ref name!, out _, out listType); @@ -911,7 +910,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + ArgumentNullException.ThrowIfNull(name); MemberListType listType; FilterHelper(bindingAttr, ref name!, out _, out listType); @@ -953,7 +952,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type? GetInterface(string fullname, bool ignoreCase) { - if (fullname == null) throw new ArgumentNullException(nameof(fullname)); + ArgumentNullException.ThrowIfNull(fullname); BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; @@ -1006,7 +1005,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type? GetNestedType(string fullname, BindingFlags bindingAttr) { - if (fullname == null) throw new ArgumentNullException(nameof(fullname)); + ArgumentNullException.ThrowIfNull(fullname); bindingAttr &= ~BindingFlags.Static; string? name, ns; @@ -1034,7 +1033,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) [DynamicallyAccessedMembers(GetAllMembers)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); ListBuilder methods = default; ListBuilder constructors = default; @@ -1116,7 +1115,7 @@ public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFla public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member) { - if (member is null) throw new ArgumentNullException(nameof(member)); + ArgumentNullException.ThrowIfNull(member); RuntimeType? runtimeType = this; while (runtimeType != null) @@ -1307,8 +1306,7 @@ public override Type[] GetGenericArguments() [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) { - if (instantiation == null) - throw new ArgumentNullException(nameof(instantiation)); + ArgumentNullException.ThrowIfNull(instantiation); RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length]; @@ -1578,16 +1576,14 @@ internal RuntimeType(object obj) internal override MethodInfo GetMethod(MethodInfo fromNoninstanciated) { - if (fromNoninstanciated == null) - throw new ArgumentNullException(nameof(fromNoninstanciated)); + ArgumentNullException.ThrowIfNull(fromNoninstanciated); var this_type = this; return (MethodInfo)GetCorrespondingInflatedMethod(new QCallTypeHandle(ref this_type), fromNoninstanciated); } internal override ConstructorInfo GetConstructor(ConstructorInfo fromNoninstanciated) { - if (fromNoninstanciated == null) - throw new ArgumentNullException(nameof(fromNoninstanciated)); + ArgumentNullException.ThrowIfNull(fromNoninstanciated); var this_type = this; return (ConstructorInfo)GetCorrespondingInflatedMethod(new QCallTypeHandle(ref this_type), fromNoninstanciated); } @@ -2125,8 +2121,7 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn if (IsGenericParameter) throw new InvalidOperationException(SR.Arg_GenericParameter); - if (ifaceType is null) - throw new ArgumentNullException(nameof(ifaceType)); + ArgumentNullException.ThrowIfNull(ifaceType); RuntimeType? ifaceRtType = ifaceType as RuntimeType; @@ -2380,8 +2375,7 @@ internal override bool IsUserType public override bool IsSubclassOf(Type type) { - if (type is null) - throw new ArgumentNullException(nameof(type)); + ArgumentNullException.ThrowIfNull(type); RuntimeType? rtType = type as RuntimeType; if (rtType == null) diff --git a/src/mono/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs b/src/mono/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs index 8f76edca8cbb30..d49f92a945bb9d 100644 --- a/src/mono/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs +++ b/src/mono/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs @@ -365,8 +365,7 @@ internal static bool IsTypeDefinition(RuntimeType type) [RequiresUnreferencedCode("Types might be removed")] internal static RuntimeType? GetTypeByName(string typeName, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); + ArgumentNullException.ThrowIfNull(typeName); if (typeName.Length == 0) if (throwOnError) diff --git a/src/mono/System.Private.CoreLib/src/System/String.Mono.cs b/src/mono/System.Private.CoreLib/src/System/String.Mono.cs index 0a661586dfaf95..780fd4fe66e248 100644 --- a/src/mono/System.Private.CoreLib/src/System/String.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/String.Mono.cs @@ -9,16 +9,14 @@ public partial class String { public static string Intern(string str) { - if (str == null) - throw new ArgumentNullException(nameof(str)); + ArgumentNullException.ThrowIfNull(str); return InternalIntern(str); } public static string IsInterned(string str) { - if (str == null) - throw new ArgumentNullException(nameof(str)); + ArgumentNullException.ThrowIfNull(str); return InternalIsInterned(str); } diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs index 7e88e31ea16117..413198df4ad480 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/Monitor.Mono.cs @@ -56,30 +56,26 @@ public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTa public static bool IsEntered(object obj) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); return IsEnteredNative(obj); } [UnsupportedOSPlatform("browser")] public static bool Wait(object obj, int millisecondsTimeout) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); return ObjWait(millisecondsTimeout, obj); } public static void Pulse(object obj) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); ObjPulse(obj); } public static void PulseAll(object obj) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); ObjPulseAll(obj); } @@ -126,8 +122,7 @@ private static bool ObjWait(int millisecondsTimeout, object obj) private static void ReliableEnterTimeout(object obj, int timeout, ref bool lockTaken) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); + ArgumentNullException.ThrowIfNull(obj); if (timeout < 0 && timeout != (int)Timeout.Infinite) throw new ArgumentOutOfRangeException(nameof(timeout)); diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/src/mono/System.Private.CoreLib/src/System/Threading/Overlapped.cs index 6838de54ba5904..fb348ab41bb5df 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -242,8 +242,7 @@ public IntPtr EventHandleIntPtr [CLSCompliant(false)] public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { - if (nativeOverlappedPtr == null) - throw new ArgumentNullException(nameof(nativeOverlappedPtr)); + ArgumentNullException.ThrowIfNull(nativeOverlappedPtr); return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped!; } @@ -251,8 +250,7 @@ public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) [CLSCompliant(false)] public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr) { - if (nativeOverlappedPtr == null) - throw new ArgumentNullException(nameof(nativeOverlappedPtr)); + ArgumentNullException.ThrowIfNull(nativeOverlappedPtr); OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped!._overlappedData = null!; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Mono.cs index 4a738976a5e2a3..8e2f33e002f6b7 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Mono.cs @@ -13,8 +13,10 @@ private ThreadPoolBoundHandle() { } - public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) + public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { + ArgumentNullException.ThrowIfNull(handle); + if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); @@ -22,8 +24,10 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) } [CLSCompliant(false)] - public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback!!, object? state, object? pinData) + public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData) { + ArgumentNullException.ThrowIfNull(callback); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); } @@ -34,21 +38,24 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle!!) [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { - if (preAllocated == null) - throw new ArgumentNullException(nameof(preAllocated)); + ArgumentNullException.ThrowIfNull(preAllocated); throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); } [CLSCompliant(false)] - public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped!!) + public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { + ArgumentNullException.ThrowIfNull(overlapped); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); } [CLSCompliant(false)] - public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped!!) + public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped) { + ArgumentNullException.ThrowIfNull(overlapped); + throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); } diff --git a/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs b/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs index 5f913b4fd28493..6d966fb43b21b8 100644 --- a/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs +++ b/src/mono/System.Private.CoreLib/src/System/TypeNameParser.cs @@ -23,8 +23,7 @@ internal static class TypeNameParser bool ignoreCase, ref StackCrawlMark stackMark) { - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); + ArgumentNullException.ThrowIfNull(typeName); ParsedName? pname = ParseName(typeName, false, 0, out int end_pos); if (pname == null) diff --git a/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs b/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs index a54d27a3de67cb..23749b5264c052 100644 --- a/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs +++ b/src/mono/System.Private.CoreLib/src/System/TypeSpec.cs @@ -256,8 +256,7 @@ internal string DisplayFullName internal static TypeSpec Parse(string typeName) { int pos = 0; - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); + ArgumentNullException.ThrowIfNull(typeName); TypeSpec res = Parse(typeName, ref pos, false, true); if (pos < typeName.Length) diff --git a/src/tests/Common/Coreclr.TestWrapper/MobileAppHandler.cs b/src/tests/Common/Coreclr.TestWrapper/MobileAppHandler.cs index 053447f6a9e371..11fd19e3f7a6b9 100644 --- a/src/tests/Common/Coreclr.TestWrapper/MobileAppHandler.cs +++ b/src/tests/Common/Coreclr.TestWrapper/MobileAppHandler.cs @@ -41,7 +41,6 @@ private static int HandleMobileApp(string action, string platform, string catego using (var outputWriter = new StreamWriter(outputStream)) using (var errorWriter = new StreamWriter(errorStream)) { - //Validate inputs if ((platform != "android") && (platform != "apple")) { outputWriter.WriteLine($"Incorrect value of platform. Provided {platform}. Valid strings are android and apple.");