diff --git a/eng/CodeAnalysis.src.globalconfig b/eng/CodeAnalysis.src.globalconfig index e5ae41903b5a76..df9d7285695cf8 100644 --- a/eng/CodeAnalysis.src.globalconfig +++ b/eng/CodeAnalysis.src.globalconfig @@ -1539,6 +1539,9 @@ 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 f56a38cfa707c0..6e8b42ea3606c7 100644 --- a/eng/CodeAnalysis.test.globalconfig +++ b/eng/CodeAnalysis.test.globalconfig @@ -1536,6 +1536,9 @@ 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/eng/Versions.props b/eng/Versions.props index 22858083014673..e828e5e89067bd 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -20,6 +20,7 @@ false false $(AssemblyVersion) + true + 4.2.0-2.22105.4 2.0.0-alpha.1.21525.11 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 3886195966ebd4..958199de5a5d44 100644 --- a/src/coreclr/System.Private.CoreLib/src/Microsoft/Win32/OAVariantLib.cs +++ b/src/coreclr/System.Private.CoreLib/src/Microsoft/Win32/OAVariantLib.cs @@ -72,12 +72,8 @@ 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!!) { - if (targetClass == null) - throw new ArgumentNullException(nameof(targetClass)); - if (culture == null) - throw new ArgumentNullException(nameof(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 90261791d0c8d5..f33849d2a949e5 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs @@ -450,14 +450,8 @@ 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) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -474,11 +468,8 @@ 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) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - return element.MemberType switch { MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit), @@ -492,15 +483,9 @@ 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) { // Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -543,14 +528,8 @@ 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) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -565,11 +544,8 @@ public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attrib return (element.GetCustomAttributes(attributeType, inherit) as Attribute[])!; } - public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) + public static Attribute[] GetCustomAttributes(ParameterInfo element!!, bool inherit) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - if (element.Member == null) throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element)); @@ -586,14 +562,9 @@ 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) { // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -653,22 +624,13 @@ 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) { - if (element == null) - throw new ArgumentNullException(nameof(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) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -680,14 +642,9 @@ 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) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -723,14 +680,8 @@ 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) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); @@ -742,11 +693,8 @@ 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) { - if (element == null) - throw new ArgumentNullException(nameof(element)); - return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } @@ -755,14 +703,9 @@ 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) { // Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk - if (element == null) - throw new ArgumentNullException(nameof(element)); - - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); 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 bb9d40bc38db3c..e63e57a3f4a11e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs @@ -33,11 +33,8 @@ IEnumerator IEnumerable.GetEnumerator() // ICollection members - public void CopyTo(Array array, int index) + public void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -58,23 +55,14 @@ public void CopyTo(Array array, int index) // IDictionary members - public object? this[object key] + public object? this[object key!!] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } return null; } set { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } - if (!key.GetType().IsSerializable) throw new ArgumentException(SR.Argument_NotSerializable, nameof(key)); @@ -94,13 +82,8 @@ public bool Contains(object key) return false; } - public void Add(object key, object? value) + public void Add(object key!!, object? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_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 23567e475d99b9..3afbff9eb08000 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs @@ -34,14 +34,8 @@ 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!!) { - if (target == null) - throw new ArgumentNullException(nameof(target)); - - if (method == null) - throw new ArgumentNullException(nameof(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 @@ -57,17 +51,10 @@ 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!!) { - if (target == null) - throw new ArgumentNullException(nameof(target)); - if (target.ContainsGenericParameters) throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target)); - - if (method == null) - throw new ArgumentNullException(nameof(method)); - if (!(target is RuntimeType rtTarget)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target)); @@ -220,15 +207,8 @@ 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) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - if (target == null) - throw new ArgumentNullException(nameof(target)); - if (method == null) - throw new ArgumentNullException(nameof(method)); - if (!(type is RuntimeType rtType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); if (!rtType.IsDelegate()) @@ -258,17 +238,10 @@ 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) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - if (target == null) - throw new ArgumentNullException(nameof(target)); if (target.ContainsGenericParameters) throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target)); - if (method == null) - throw new ArgumentNullException(nameof(method)); - if (!(type is RuntimeType rtType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); if (!(target is RuntimeType rtTarget)) @@ -297,13 +270,9 @@ 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. - if (type == null) - throw new ArgumentNullException(nameof(type)); - if (method == null) - throw new ArgumentNullException(nameof(method)); if (!(type is RuntimeType rtType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); @@ -374,11 +343,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. - if (type == null) - throw new ArgumentNullException(nameof(type)); if (method.IsNullHandle()) throw new ArgumentNullException(nameof(method)); diff --git a/src/coreclr/System.Private.CoreLib/src/System/GC.cs b/src/coreclr/System.Private.CoreLib/src/System/GC.cs index 7597672f683164..3e28ba7d3947d5 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/GC.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/GC.cs @@ -303,10 +303,8 @@ 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!!) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); _SuppressFinalize(obj); } @@ -317,10 +315,8 @@ 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!!) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); _ReRegisterForFinalize(obj); } @@ -609,10 +605,7 @@ internal static void RegisterMemoryLoadChangeNotification(float lowMemoryPercent { throw new ArgumentOutOfRangeException(nameof(lowMemoryPercent)); } - if (notification == null) - { - throw new ArgumentNullException(nameof(notification)); - } + ArgumentNullException.ThrowIfNull(notification); lock (s_notifications) { @@ -625,13 +618,8 @@ internal static void RegisterMemoryLoadChangeNotification(float lowMemoryPercent } } - internal static void UnregisterMemoryLoadChangeNotification(Action notification) + internal static void UnregisterMemoryLoadChangeNotification(Action notification!!) { - if (notification == null) - { - throw new ArgumentNullException(nameof(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 282d713232b660..651c4aed685f46 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,11 +23,8 @@ 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!!) { - if (partialName == null) - throw new ArgumentNullException(nameof(partialName)); - if ((partialName.Length == 0) || (partialName[0] == '\0')) throw new ArgumentException(SR.Format_StringZeroLength, nameof(partialName)); @@ -45,11 +42,8 @@ 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!!) { - if (assemblyRef == null) - throw new ArgumentNullException(nameof(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 e146d3a5853d42..b821a1141fa75a 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 @@ -57,16 +57,12 @@ internal ModuleBuilder GetModuleBuilder(RuntimeModule module) #region Constructor - internal AssemblyBuilder(AssemblyName name, + internal AssemblyBuilder(AssemblyName name!!, AssemblyBuilderAccess access, Assembly? callingAssembly, AssemblyLoadContext? assemblyLoadContext, IEnumerable? unsafeAssemblyAttributes) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access)); @@ -371,17 +367,8 @@ 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!!) { - if (con == null) - { - throw new ArgumentNullException(nameof(con)); - } - if (binaryAttribute == null) - { - throw new ArgumentNullException(nameof(binaryAttribute)); - } - lock (SyncRoot) { TypeBuilder.DefineCustomAttribute( @@ -395,13 +382,8 @@ 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!!) { - if (customBuilder == null) - { - throw new ArgumentNullException(nameof(customBuilder)); - } - lock (SyncRoot) { customBuilder.CreateCustomAttribute(_manifestModuleBuilder, AssemblyBuilderData.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 1038d9ba86504a..f910b8a7e7da0d 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,20 +48,8 @@ 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!!) { - 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)); #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 ff832cff7e14a2..d5d36a60b4231f 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,11 +32,9 @@ 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) { LocalBuilder localBuilder; - if (localType == null) - throw new ArgumentNullException(nameof(localType)); RuntimeType? rtType = localType as RuntimeType; @@ -55,11 +53,8 @@ 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!!) { - if (meth == null) - throw new ArgumentNullException(nameof(meth)); - int stackchange = 0; int token; DynamicMethod? dynMeth = meth as DynamicMethod; @@ -110,11 +105,8 @@ 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!!) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - RuntimeConstructorInfo? rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(con)); @@ -137,11 +129,8 @@ 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!!) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - RuntimeType? rtType = type as RuntimeType; if (rtType == null) @@ -153,11 +142,8 @@ 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!!) { - if (field == null) - throw new ArgumentNullException(nameof(field)); - RuntimeFieldInfo? runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(field)); @@ -173,11 +159,8 @@ 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!!) { - if (str == null) - throw new ArgumentNullException(nameof(str)); - int tempVal = GetTokenForString(str); EnsureCapacity(7); InternalEmit(opcode); @@ -264,11 +247,8 @@ 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) { - if (methodInfo == null) - throw new ArgumentNullException(nameof(methodInfo)); - if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode)); @@ -303,11 +283,8 @@ public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? opti PutInteger4(tk); } - public override void Emit(OpCode opcode, SignatureHelper signature) + public override void Emit(OpCode opcode, SignatureHelper signature!!) { - if (signature == null) - throw new ArgumentNullException(nameof(signature)); - int stackchange = 0; EnsureCapacity(7); InternalEmit(opcode); @@ -376,8 +353,7 @@ public override void BeginCatchBlock(Type exceptionType) else { // execute this branch if previous clause is Catch or Fault - if (exceptionType == null) - throw new ArgumentNullException(nameof(exceptionType)); + ArgumentNullException.ThrowIfNull(exceptionType); if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -895,8 +871,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); m_code = new Span(code, codeSize).ToArray(); m_maxStackSize = maxStackSize; @@ -913,8 +889,8 @@ public unsafe void SetExceptions(byte* exceptions, int exceptionsSize) if (exceptionsSize < 0) throw new ArgumentOutOfRangeException(nameof(exceptionsSize), SR.ArgumentOutOfRange_GenericPositive); - if (exceptionsSize > 0 && exceptions == null) - throw new ArgumentNullException(nameof(exceptions)); + if (exceptionsSize > 0) + ArgumentNullException.ThrowIfNull(exceptions); m_exceptions = new Span(exceptions, exceptionsSize).ToArray(); } @@ -930,8 +906,8 @@ public unsafe void SetLocalSignature(byte* localSignature, int signatureSize) if (signatureSize < 0) throw new ArgumentOutOfRangeException(nameof(signatureSize), SR.ArgumentOutOfRange_GenericPositive); - if (signatureSize > 0 && localSignature == null) - throw new ArgumentNullException(nameof(localSignature)); + if (signatureSize > 0) + ArgumentNullException.ThrowIfNull(localSignature); m_localSignature = new Span(localSignature, signatureSize).ToArray(); } 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 b971f07e8f9811..e1819a363d3866 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 @@ -83,11 +83,8 @@ public DynamicMethod(string name, public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, - Module m) + Module m!!) { - if (m == null) - throw new ArgumentNullException(nameof(m)); - Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, @@ -102,12 +99,9 @@ public DynamicMethod(string name, public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, - Module m, + Module m!!, bool skipVisibility) { - if (m == null) - throw new ArgumentNullException(nameof(m)); - Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, @@ -124,12 +118,9 @@ public DynamicMethod(string name, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, - Module m, + Module m!!, bool skipVisibility) { - if (m == null) - throw new ArgumentNullException(nameof(m)); - Init(name, attributes, callingConvention, @@ -144,11 +135,8 @@ public DynamicMethod(string name, public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, - Type owner) + Type owner!!) { - if (owner == null) - throw new ArgumentNullException(nameof(owner)); - Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, @@ -163,12 +151,9 @@ public DynamicMethod(string name, public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, - Type owner, + Type owner!!, bool skipVisibility) { - if (owner == null) - throw new ArgumentNullException(nameof(owner)); - Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, @@ -185,12 +170,9 @@ public DynamicMethod(string name, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, - Type owner, + Type owner!!, bool skipVisibility) { - if (owner == null) - throw new ArgumentNullException(nameof(owner)); - Init(name, attributes, callingConvention, @@ -253,17 +235,17 @@ private static RuntimeModule GetDynamicMethodsModule() [MemberNotNull(nameof(m_parameterTypes))] [MemberNotNull(nameof(m_returnType))] [MemberNotNull(nameof(m_dynMethod))] - private void Init(string name, - MethodAttributes attributes, - CallingConventions callingConvention, - Type? returnType, - Type[]? signature, - Type? owner, - Module? m, - bool skipVisibility, - bool transparentMethod) + private void Init(string name!!, + MethodAttributes attributes, + CallingConventions callingConvention, + Type? returnType, + Type[]? signature, + Type? owner, + Module? m, + bool skipVisibility, + bool transparentMethod) { - DynamicMethod.CheckConsistency(attributes, callingConvention); + CheckConsistency(attributes, callingConvention); // check and store the signature if (signature != null) @@ -329,10 +311,6 @@ private void Init(string name, m_ilGenerator = null; m_fInitLocals = true; m_methodHandle = null; - - if (name == null) - throw new ArgumentNullException(nameof(name)); - m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); } @@ -655,11 +633,8 @@ 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 == null) - throw new ArgumentNullException(nameof(attributeType)); - if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return true; else 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 be0ed200842094..c393d8dd1d6857 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,13 +46,8 @@ internal int GetEventToken() return m_evToken; } - private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics) + private void SetMethodSemantics(MethodBuilder mdBuilder!!, MethodSemanticsAttributes semantics) { - if (mdBuilder == null) - { - throw new ArgumentNullException(nameof(mdBuilder)); - } - m_type.ThrowIfCreated(); ModuleBuilder module = m_module; TypeBuilder.DefineMethodSemantics( @@ -84,12 +79,8 @@ 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!!) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); m_type.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute( @@ -100,12 +91,8 @@ 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!!) { - if (customBuilder == null) - { - throw new ArgumentNullException(nameof(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 c3e22c5d340719..5c65ff31c00b67 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,14 +154,8 @@ 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!!) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); - ModuleBuilder module = (m_typeBuilder.Module as ModuleBuilder)!; m_typeBuilder.ThrowIfCreated(); @@ -170,11 +164,8 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) m_fieldTok, module.GetConstructorToken(con), binaryAttribute); } - public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(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 1b35f5cdbb15f0..65d97cd384e7d3 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,11 +474,8 @@ 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!!) { - if (meth == null) - throw new ArgumentNullException(nameof(meth)); - if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)) { EmitCall(opcode, meth, null); @@ -586,11 +583,8 @@ 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) { - if (methodInfo == null) - throw new ArgumentNullException(nameof(methodInfo)); - if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode)); @@ -621,11 +615,8 @@ public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optio PutInteger4(tk); } - public virtual void Emit(OpCode opcode, SignatureHelper signature) + public virtual void Emit(OpCode opcode, SignatureHelper signature!!) { - if (signature == null) - throw new ArgumentNullException(nameof(signature)); - int stackchange = 0; ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module; int sig = modBuilder.GetSignatureToken(signature); @@ -655,11 +646,8 @@ 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!!) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - int stackchange = 0; // Constructors cannot be generic so the value of UseMethodDef doesn't matter. @@ -772,11 +760,8 @@ public virtual void Emit(OpCode opcode, Label label) } } - public virtual void Emit(OpCode opcode, Label[] labels) + public virtual void Emit(OpCode opcode, Label[] labels!!) { - if (labels == null) - throw new ArgumentNullException(nameof(labels)); - // Emitting a switch table int i; @@ -818,14 +803,9 @@ 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!!) { // Puts the opcode onto the IL stream followed by the information for local variable local. - - if (local == null) - { - throw new ArgumentNullException(nameof(local)); - } int tempVal = local.GetLocalIndex(); if (local.GetMethodBuilder() != m_methodBuilder) { @@ -1022,10 +1002,7 @@ public virtual void BeginCatchBlock(Type exceptionType) else { // execute this branch if previous clause is Catch or Fault - if (exceptionType == null) - { - throw new ArgumentNullException(nameof(exceptionType)); - } + ArgumentNullException.ThrowIfNull(exceptionType); Emit(OpCodes.Leave, current.GetEndLabel()); } @@ -1188,18 +1165,13 @@ public virtual void EmitWriteLine(LocalBuilder localBuilder) Emit(OpCodes.Callvirt, mi); } - public virtual void EmitWriteLine(FieldInfo fld) + public virtual void EmitWriteLine(FieldInfo 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. // we do *not* call ToString on the fields. - if (fld == null) - { - throw new ArgumentNullException(nameof(fld)); - } - Type consoleType = Type.GetType(ConsoleTypeFullName, throwOnError: true)!; MethodInfo prop = consoleType.GetMethod("get_Out")!; Emit(OpCodes.Call, prop); @@ -1252,10 +1224,7 @@ public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated); } - if (localType == null) - { - throw new ArgumentNullException(nameof(localType)); - } + ArgumentNullException.ThrowIfNull(localType); if (methodBuilder.m_bIsBaked) { 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 9d11aacaf53ea8..8c1c738f0d390b 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,14 +130,10 @@ internal MethodBuilder(string name, MethodAttributes attributes, CallingConventi #region Internal Members - internal void CreateMethodBodyHelper(ILGenerator il) + internal void CreateMethodBodyHelper(ILGenerator 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. - if (il == null) - { - throw new ArgumentNullException(nameof(il)); - } __ExceptionInfo[] excp; int counter = 0; @@ -517,11 +513,8 @@ public override MethodInfo MakeGenericMethod(params Type[] typeArguments) return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } - public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) + public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names!!) { - if (names == null) - throw new ArgumentNullException(nameof(names)); - if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); @@ -529,8 +522,7 @@ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] nam throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); for (int i = 0; i < names.Length; i++) - if (names[i] == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(names[i], nameof(names)); if (m_token != 0) throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked); @@ -734,13 +726,8 @@ internal Module GetModule() return GetModuleBuilder(); } - public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { - if (con is null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute is null) - throw new ArgumentNullException(nameof(binaryAttribute)); - ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataToken, @@ -751,11 +738,8 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) ParseCA(con); } - public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(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 f1ffa97874925f..3bf175e13e1f62 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 @@ -216,14 +216,9 @@ private int GetTypeRefNested(Type type, Module? refedModule, string? strRefedMod return GetTypeRef(new QCallModule(ref thisModule), typeName, new QCallModule(ref refedRuntimeModule), strRefedModuleFileName, tkResolution); } - internal int InternalGetConstructorToken(ConstructorInfo con, bool usingRef) + internal int InternalGetConstructorToken(ConstructorInfo con!!, bool usingRef) { // Helper to get constructor token. If usingRef is true, we will never use the def token - if (con == null) - { - throw new ArgumentNullException(nameof(con)); - } - int tr; int mr; @@ -1033,13 +1028,8 @@ internal int GetTypeToken(Type type) return GetTypeTokenInternal(type, getGenericDefinition: true); } - private int GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition) + private int GetTypeTokenWorkerNoLock(Type type!!, bool getGenericDefinition) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - AssemblyBuilder.CheckContext(type); // Return a token for the class relative to the Module. Tokens @@ -1131,15 +1121,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) { // Return a MemberRef token if MethodInfo is not defined in this module. Or // return the MethodDef token. - if (method == null) - { - throw new ArgumentNullException(nameof(method)); - } - int tr; int mr; @@ -1370,13 +1355,8 @@ internal int GetFieldToken(FieldInfo field) } } - private int GetFieldTokenNoLock(FieldInfo field) + private int GetFieldTokenNoLock(FieldInfo field!!) { - if (field == null) - { - throw new ArgumentNullException(nameof(field)); - } - int tr; int mr; @@ -1448,41 +1428,26 @@ private int GetFieldTokenNoLock(FieldInfo field) return mr; } - internal int GetStringConstant(string str) + internal int GetStringConstant(string str!!) { - if (str == null) - { - throw new ArgumentNullException(nameof(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!!) { // Define signature token given a signature helper. This will define a metadata // token for the signature described by SignatureHelper. - if (sigHelper == null) - { - throw new ArgumentNullException(nameof(sigHelper)); - } - - // get the signature in byte form + // Get the signature in byte form. byte[] sigBytes = sigHelper.InternalGetSignature(out int sigLength); ModuleBuilder thisModule = this; return TypeBuilder.GetTokenFromSig(new QCallModule(ref thisModule), sigBytes, sigLength); } - internal int GetSignatureToken(byte[] sigBytes, int sigLength) + internal int GetSignatureToken(byte[] sigBytes!!, int sigLength) { - if (sigBytes == null) - { - throw new ArgumentNullException(nameof(sigBytes)); - } - byte[] localSigBytes = new byte[sigBytes.Length]; Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length); @@ -1494,17 +1459,8 @@ internal int GetSignatureToken(byte[] sigBytes, int sigLength) #region Other - public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { - if (con == null) - { - throw new ArgumentNullException(nameof(con)); - } - if (binaryAttribute == null) - { - throw new ArgumentNullException(nameof(binaryAttribute)); - } - TypeBuilder.DefineCustomAttribute( this, 1, // This is hard coding the module token to 1 @@ -1512,13 +1468,8 @@ public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) binaryAttribute); } - public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { - if (customBuilder == null) - { - throw new ArgumentNullException(nameof(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 79379c535874c7..6be9a88cfe9210 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,17 +18,8 @@ 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!!) { - if (con == null) - { - throw new ArgumentNullException(nameof(con)); - } - if (binaryAttribute == null) - { - throw new ArgumentNullException(nameof(binaryAttribute)); - } - TypeBuilder.DefineCustomAttribute( _methodBuilder.GetModuleBuilder(), _token, @@ -37,12 +28,8 @@ 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!!) { - if (customBuilder == null) - { - throw new ArgumentNullException(nameof(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 89accc39caeb98..71dfd932e12605 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 @@ -67,13 +67,8 @@ 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) { - if (mdBuilder == null) - { - throw new ArgumentNullException(nameof(mdBuilder)); - } - m_containingType.ThrowIfCreated(); ModuleBuilder module = m_moduleBuilder; TypeBuilder.DefineMethodSemantics( @@ -102,13 +97,8 @@ 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!!) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); - m_containingType.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute( m_moduleBuilder, @@ -118,12 +108,8 @@ 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!!) { - if (customBuilder == null) - { - throw new ArgumentNullException(nameof(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 9dd3a2fbb63e89..cacb7ac0121c55 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,14 +167,8 @@ 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!!) { - if (module == null) - throw new ArgumentNullException(nameof(module)); - - if (type == null) - throw new ArgumentNullException(nameof(type)); - return new SignatureHelper(module, type); } #endregion @@ -308,8 +302,7 @@ private void AddOneArgTypeHelper(Type clsArgument, Type[]? requiredCustomModifie { Type t = requiredCustomModifiers[i]; - if (t == null) - throw new ArgumentNullException(nameof(requiredCustomModifiers)); + ArgumentNullException.ThrowIfNull(t, nameof(requiredCustomModifiers)); if (t.HasElementType) throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(requiredCustomModifiers)); @@ -746,11 +739,8 @@ public void AddArgument(Type clsArgument) AddArgument(clsArgument, null, null); } - public void AddArgument(Type argument, bool pinned) + public void AddArgument(Type argument!!, bool pinned) { - if (argument == null) - throw new ArgumentNullException(nameof(argument)); - IncrementArgCounts(); AddOneArgTypeHelper(argument, pinned); } @@ -777,8 +767,7 @@ public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? if (m_sigDone) throw new ArgumentException(SR.Argument_SigIsFinalized); - if (argument == null) - throw new ArgumentNullException(nameof(argument)); + ArgumentNullException.ThrowIfNull(argument); IncrementArgCounts(); 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 f714e5ebd59975..735956362086dd 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,11 +224,8 @@ internal SymbolType(TypeKind typeKind) #endregion #region Internal Members - internal void SetElementType(Type baseType) + internal void SetElementType(Type baseType!!) { - if (baseType is null) - throw new ArgumentNullException(nameof(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 ad80acad078350..0f353d383e0afb 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,23 +25,14 @@ 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!!) { - if (con is null) - throw new ArgumentNullException(nameof(con)); - - if (binaryAttribute is null) - throw new ArgumentNullException(nameof(binaryAttribute)); - m_con = con; m_binaryAttribute = binaryAttribute; } - public CustAttr(CustomAttributeBuilder customBuilder) + public CustAttr(CustomAttributeBuilder customBuilder!!) { - if (customBuilder is null) - throw new ArgumentNullException(nameof(customBuilder)); - m_customBuilder = customBuilder; } @@ -509,11 +500,8 @@ internal TypeBuilder( { for (i = 0; i < interfaces.Length; i++) { - if (interfaces[i] == null) - { - // cannot contain null in the interface list - throw new ArgumentNullException(nameof(interfaces)); - } + // cannot contain null in the interface list + ArgumentNullException.ThrowIfNull(interfaces[i], nameof(interfaces)); } interfaceTokens = new int[interfaces.Length + 1]; for (i = 0; i < interfaces.Length; i++) @@ -1120,8 +1108,7 @@ public override object[] GetCustomAttributes(Type attributeType, bool inherit) if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(attributeType); if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -1134,8 +1121,7 @@ public override bool IsDefined(Type attributeType, bool inherit) if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); + ArgumentNullException.ThrowIfNull(attributeType); if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -1161,17 +1147,13 @@ internal void SetInterfaces(params Type[]? interfaces) } } - public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) + public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names!!) { - if (names == null) - throw new ArgumentNullException(nameof(names)); - if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); for (int i = 0; i < names.Length; i++) - if (names[i] == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(names[i], nameof(names)); if (m_inst != null) throw new InvalidOperationException(); @@ -1214,14 +1196,8 @@ public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInf } } - private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) + private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody!!, MethodInfo methodInfoDeclaration!!) { - if (methodInfoBody == null) - throw new ArgumentNullException(nameof(methodInfoBody)); - - if (methodInfoDeclaration == null) - throw new ArgumentNullException(nameof(methodInfoDeclaration)); - ThrowIfCreated(); if (!ReferenceEquals(methodInfoBody.DeclaringType, this)) @@ -1700,11 +1676,8 @@ 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) { - if (data == null) - throw new ArgumentNullException(nameof(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. @@ -2096,13 +2069,8 @@ public void SetParent([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes } } - public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType) + public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType!!) { - if (interfaceType == null) - { - throw new ArgumentNullException(nameof(interfaceType)); - } - AssemblyBuilder.CheckContext(interfaceType); ThrowIfCreated(); @@ -2125,23 +2093,14 @@ internal int TypeToken } } - public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) + public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { - if (con == null) - throw new ArgumentNullException(nameof(con)); - - if (binaryAttribute == null) - throw new ArgumentNullException(nameof(binaryAttribute)); - DefineCustomAttribute(m_module, m_tdType, ((ModuleBuilder)m_module).GetConstructorToken(con), binaryAttribute); } - public void SetCustomAttribute(CustomAttributeBuilder customBuilder) + public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { - if (customBuilder == null) - throw new ArgumentNullException(nameof(customBuilder)); - customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index 3f2cadc852e6af..4e195408633ece 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -24,13 +24,11 @@ internal static Type MakeGenericType(Type type, Type[] typeArguments) if (!type.IsGenericTypeDefinition) throw new InvalidOperationException(); - if (typeArguments == null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(typeArguments); foreach (Type t in typeArguments) { - if (t == null) - throw new ArgumentNullException(nameof(typeArguments)); + ArgumentNullException.ThrowIfNull(t, nameof(typeArguments)); } return new TypeBuilderInstantiation(type, typeArguments); 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 7d5736ee88de11..fe79a0e8e7c83f 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,11 +7,8 @@ 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 { - if (other is null) - throw new ArgumentNullException(nameof(other)); - // Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it! 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 332dd6301cde09..fa7385a02dfc66 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,13 +28,8 @@ 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) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - blob = null; length = 0; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs index 87366de57eb010..462df732af729c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs @@ -36,7 +36,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/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index 11a0aa3afa1a71..1b66fb3c8244c1 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -184,12 +184,10 @@ private static partial void GetType(QCallAssembly assembly, ObjectHandleOnStack assemblyLoadContext); [RequiresUnreferencedCode("Types might be removed")] - public override Type? GetType(string name, bool throwOnError, bool ignoreCase) + public override Type? GetType( + string name!!, // throw on null strings regardless of the value of "throwOnError" + bool throwOnError, bool ignoreCase) { - // throw on null strings regardless of the value of "throwOnError" - if (name == null) - throw new ArgumentNullException(nameof(name)); - RuntimeType? type = null; object? keepAlive = null; AssemblyLoadContext? assemblyLoadContextStack = AssemblyLoadContext.CurrentContextualReflectionContext; @@ -262,8 +260,8 @@ public override bool IsCollectible // Load a resource based on the NameSpace of the type. public override Stream? GetManifestResourceStream(Type type, string name) { - if (type == null && name == null) - throw new ArgumentNullException(nameof(type)); + if (name == null) + ArgumentNullException.ThrowIfNull(type); string? nameSpace = type?.Namespace; @@ -304,22 +302,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -576,11 +568,8 @@ 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) { - if (culture == null) - throw new ArgumentNullException(nameof(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 7f34d5438c6bea..267b738794a63a 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 @@ -115,22 +115,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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 edf7aeb269c26b..b6ab1bf4e45fa9 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeCustomAttributeData.cs @@ -679,11 +679,8 @@ private static extern void ParseAttributeArguments( internal static void ParseAttributeArguments(ConstArray attributeBlob, ref CustomAttributeCtorParameter[] customAttributeCtorParameters, ref CustomAttributeNamedParameter[] customAttributeNamedParameters, - RuntimeModule customAttributeModule) + RuntimeModule customAttributeModule!!) { - if (customAttributeModule is null) - throw new ArgumentNullException(nameof(customAttributeModule)); - Debug.Assert(customAttributeCtorParameters is not null); Debug.Assert(customAttributeNamedParameters is not null); @@ -713,11 +710,8 @@ 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) { - if (argumentName is null) - throw new ArgumentNullException(nameof(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 6abf767636e0dd..b0d5805804208c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs @@ -76,22 +76,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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 10605ef5f533c1..d2ddb1f36091c1 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs @@ -61,22 +61,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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 43984c60a5468d..2b26b90cb7770f 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 @@ -205,22 +205,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -417,12 +411,9 @@ 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. - if (delegateType == null) - throw new ArgumentNullException(nameof(delegateType)); - RuntimeType? rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType)); @@ -443,11 +434,8 @@ private Delegate CreateDelegateInternal(Type delegateType, object? firstArgument #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!!) { - if (methodInstantiation == null) - throw new ArgumentNullException(nameof(methodInstantiation)); - RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) @@ -457,9 +445,7 @@ public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) for (int i = 0; i < methodInstantiation.Length; i++) { Type methodInstantiationElem = methodInstantiation[i]; - - if (methodInstantiationElem == null) - throw new ArgumentNullException(); + ArgumentNullException.ThrowIfNull(methodInstantiationElem, null); RuntimeType? rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; 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 e8b52d01d5e0da..4b5760f14c713e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs @@ -385,22 +385,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -420,12 +414,10 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } [RequiresUnreferencedCode("Types might be removed")] - public override Type? GetType(string className, bool throwOnError, bool ignoreCase) + public override Type? GetType( + string className!!, // throw on null strings regardless of the value of "throwOnError" + bool throwOnError, bool ignoreCase) { - // throw on null strings regardless of the value of "throwOnError" - if (className == null) - throw new ArgumentNullException(nameof(className)); - RuntimeType? retType = null; object? keepAlive = null; RuntimeModule thisAsLocal = this; @@ -483,15 +475,9 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - - if (RuntimeType == null) - return null; - - return RuntimeType.GetField(name, bindingAttr); + return RuntimeType?.GetField(name, bindingAttr); } [RequiresUnreferencedCode("Methods might be removed")] 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 173caf6855a0aa..33777c745dbfcb 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs @@ -507,11 +507,8 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(attributeType)); - if (MdToken.IsNullToken(m_tkParamDef)) return Array.Empty(); @@ -521,11 +518,8 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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 a768a983ba6b8e..1b6c630470c3a1 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs @@ -137,22 +137,16 @@ 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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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) { - if (attributeType == null) - throw new ArgumentNullException(nameof(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/RuntimeHelpers.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs index 696b33428efc5e..953fbff5509313 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.CoreCLR.cs @@ -160,11 +160,7 @@ public static object GetUninitializedObject( { if (type is not RuntimeType rt) { - if (type is null) - { - throw new ArgumentNullException(nameof(type), SR.ArgumentNull_Type); - } - + ArgumentNullException.ThrowIfNull(type); throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type)); } 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 45807f72ab2cc1..b3e7c67442eaf3 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,9 +10,8 @@ internal sealed class TypeDependencyAttribute : Attribute { private readonly string typeName; - public TypeDependencyAttribute(string typeName) + public TypeDependencyAttribute(string typeName!!) { - if (typeName == null) throw new ArgumentNullException(nameof(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 0be7527408c885..7e5d4a3f2d208e 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 @@ -95,11 +95,8 @@ 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) { - if (instance == null) - throw new ArgumentNullException(nameof(instance)); - return TryGetOrCreateComInterfaceForObjectInternal(ObjectHandleOnStack.Create(ref impl), impl.id, ObjectHandleOnStack.Create(ref instance), flags, out retValue); } @@ -206,11 +203,8 @@ 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) { - if (wrapper == null) - throw new ArgumentNullException(nameof(wrapper)); - object? obj; if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, inner, flags, wrapper, out obj)) throw new ArgumentNullException(nameof(externalComObject)); @@ -239,8 +233,7 @@ private static bool TryGetOrCreateObjectForComInstanceInternal( object? wrapperMaybe, out object? retValue) { - if (externalComObject == IntPtr.Zero) - throw new ArgumentNullException(nameof(externalComObject)); + ArgumentNullException.ThrowIfNull(externalComObject); // If the inner is supplied the Aggregation flag should be set. if (innerMaybe != IntPtr.Zero && !flags.HasFlag(CreateObjectFlags.Aggregation)) @@ -269,11 +262,8 @@ 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!!) { - if (instance == null) - throw new ArgumentNullException(nameof(instance)); - if (null != Interlocked.CompareExchange(ref s_globalInstanceForTrackerSupport, instance, null)) { throw new InvalidOperationException(SR.InvalidOperation_ResetGlobalComWrappersInstance); @@ -301,11 +291,8 @@ public static void RegisterForTrackerSupport(ComWrappers instance) /// * COM activation /// [SupportedOSPlatform("windows")] - public static void RegisterForMarshalling(ComWrappers instance) + public static void RegisterForMarshalling(ComWrappers instance!!) { - if (instance == null) - throw new ArgumentNullException(nameof(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 c6a27d62c095f1..6a93d2b5ebd84c 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,13 +8,8 @@ namespace System.Runtime.InteropServices.CustomMarshalers { internal sealed class EnumVariantViewOfEnumerator : ComTypes.IEnumVARIANT, ICustomAdapter { - public EnumVariantViewOfEnumerator(IEnumerator enumerator) + public EnumVariantViewOfEnumerator(IEnumerator enumerator!!) { - if (enumerator is null) - { - throw new ArgumentNullException(nameof(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 adc6338feb544f..eef801c7fe4fb5 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,22 +32,14 @@ public int GetNativeDataSize() return -1; } - public IntPtr MarshalManagedToNative(object ManagedObj) + public IntPtr MarshalManagedToNative(object ManagedObj!!) { - if (ManagedObj == null) - { - throw new ArgumentNullException(nameof(ManagedObj)); - } - return Marshal.GetComInterfaceForObject(ManagedObj); } public object MarshalNativeToManaged(IntPtr pNativeData) { - if (pNativeData == IntPtr.Zero) - { - throw new ArgumentNullException(nameof(pNativeData)); - } + ArgumentNullException.ThrowIfNull(pNativeData); object comObject = Marshal.GetObjectForIUnknown(pNativeData); 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 997d22d343f090..f360e169c496fd 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,13 +33,8 @@ public int GetNativeDataSize() return -1; } - public IntPtr MarshalManagedToNative(object ManagedObj) + public IntPtr MarshalManagedToNative(object ManagedObj!!) { - if (ManagedObj == null) - { - throw new ArgumentNullException(nameof(ManagedObj)); - } - if (ManagedObj is EnumeratorViewOfEnumVariant view) { return Marshal.GetComInterfaceForObject(view.GetUnderlyingObject()); @@ -52,10 +47,7 @@ public IntPtr MarshalManagedToNative(object ManagedObj) public object MarshalNativeToManaged(IntPtr pNativeData) { - if (pNativeData == IntPtr.Zero) - { - throw new ArgumentNullException(nameof(pNativeData)); - } + ArgumentNullException.ThrowIfNull(pNativeData); object comObject = Marshal.GetObjectForIUnknown(pNativeData); 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 e8a0ae8fd35ae4..fcd63c2b84b814 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 @@ -28,13 +28,8 @@ 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.")] - public static IntPtr OffsetOf(Type t, string fieldName) + public static IntPtr OffsetOf(Type t!!, string fieldName) { - if (t is null) - { - throw new ArgumentNullException(nameof(t)); - } - FieldInfo? f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (f is null) @@ -235,13 +230,8 @@ 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!!) { - if (m is null) - { - throw new ArgumentNullException(nameof(m)); - } - if (m is RuntimeModule rtModule) { return GetHINSTANCE(new QCallModule(ref rtModule)); @@ -271,13 +261,8 @@ 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!!) { - if (typeInfo is null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } - typeInfo.GetDocumentation(-1, out string strTypeLibName, out _, out _, out _); return strTypeLibName; } @@ -309,13 +294,8 @@ 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!!) { - if (o is null) - { - throw new ArgumentNullException(nameof(o)); - } - return GetIUnknownForObjectNative(o); } @@ -326,13 +306,8 @@ 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!!) { - if (o is null) - { - throw new ArgumentNullException(nameof(o)); - } - return GetIDispatchForObjectNative(o); } @@ -344,18 +319,8 @@ public static string GetTypeInfoName(ITypeInfo typeInfo) /// Object o should support Type T /// [SupportedOSPlatform("windows")] - public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T) + public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o!!, Type T!!) { - if (o is null) - { - throw new ArgumentNullException(nameof(o)); - } - - if (T is null) - { - throw new ArgumentNullException(nameof(T)); - } - return GetComInterfaceForObjectNative(o, T, true); } @@ -368,18 +333,8 @@ public static string GetTypeInfoName(ITypeInfo typeInfo) /// invoke customized QueryInterface or not. /// [SupportedOSPlatform("windows")] - public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode) + public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o!!, Type T!!, CustomQueryInterfaceMode mode) { - if (o is null) - { - throw new ArgumentNullException(nameof(o)); - } - - if (T is null) - { - throw new ArgumentNullException(nameof(T)); - } - bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false); return GetComInterfaceForObjectNative(o, T, bEnableCustomizedQueryInterface); } @@ -393,10 +348,7 @@ public static string GetTypeInfoName(ITypeInfo typeInfo) [SupportedOSPlatform("windows")] public static object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk) { - if (pUnk == IntPtr.Zero) - { - throw new ArgumentNullException(nameof(pUnk)); - } + ArgumentNullException.ThrowIfNull(pUnk); return GetObjectForIUnknownNative(pUnk); } @@ -407,10 +359,7 @@ public static object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk) [SupportedOSPlatform("windows")] public static object GetUniqueObjectForIUnknown(IntPtr unknown) { - if (unknown == IntPtr.Zero) - { - throw new ArgumentNullException(nameof(unknown)); - } + ArgumentNullException.ThrowIfNull(unknown); return GetUniqueObjectForIUnknownNative(unknown); } @@ -466,13 +415,8 @@ 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!!) { - if (o is null) - { - throw new ArgumentNullException(nameof(o)); - } - return o is __ComObject; } @@ -516,10 +460,7 @@ public static int FinalReleaseComObject(object o) throw new NotSupportedException(SR.NotSupported_COM); } - if (o is null) - { - throw new ArgumentNullException(nameof(o)); - } + ArgumentNullException.ThrowIfNull(o); if (!(o is __ComObject co)) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); @@ -540,14 +481,8 @@ public static int FinalReleaseComObject(object o) throw new NotSupportedException(SR.NotSupported_COM); } - if (obj is null) - { - throw new ArgumentNullException(nameof(obj)); - } - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(obj); + ArgumentNullException.ThrowIfNull(key); if (!(obj is __ComObject co)) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj)); @@ -571,14 +506,8 @@ public static bool SetComObjectData(object obj, object key, object? data) throw new NotSupportedException(SR.NotSupported_COM); } - if (obj is null) - { - throw new ArgumentNullException(nameof(obj)); - } - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(obj); + ArgumentNullException.ThrowIfNull(key); if (!(obj is __ComObject co)) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(obj)); @@ -601,10 +530,7 @@ public static bool SetComObjectData(object obj, object key, object? data) throw new NotSupportedException(SR.NotSupported_COM); } - if (t is null) - { - throw new ArgumentNullException(nameof(t)); - } + ArgumentNullException.ThrowIfNull(t); if (!t.IsCOMObject) { throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t)); 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 454d5ef1b8d8e9..189544527f65b5 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 @@ -81,10 +81,8 @@ internal unsafe Assembly InternalLoad(ReadOnlySpan arrAssembly, ReadOnlySp /// internal Assembly LoadFromInMemoryModule(IntPtr moduleHandle) { - if (moduleHandle == IntPtr.Zero) - { - throw new ArgumentNullException(nameof(moduleHandle)); - } + ArgumentNullException.ThrowIfNull(moduleHandle); + lock (_unloadLock) { VerifyIsAlive(); @@ -138,18 +136,12 @@ 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!!) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - - AssemblyLoadContext? loadContextForAssembly = null; - RuntimeAssembly? rtAsm = GetRuntimeAssembly(assembly); // We only support looking up load context for runtime assemblies. + AssemblyLoadContext? loadContextForAssembly = null; if (rtAsm != null) { RuntimeAssembly runtimeAssembly = rtAsm; 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 bf83df6c0f9751..0e966a690f4194 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -1719,12 +1719,9 @@ 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) { - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); - return RuntimeTypeHandle.GetTypeByName( typeName, throwOnError, ignoreCase, ref stackMark); } @@ -2669,8 +2666,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; @@ -2812,10 +2808,8 @@ 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) { - if (name == null) throw new ArgumentNullException(nameof(name)); - ListBuilder candidates = GetPropertyCandidates(name, bindingAttr, types, false); if (candidates.Count == 0) @@ -2849,10 +2843,8 @@ 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) { - if (name is null) throw new ArgumentNullException(nameof(name)); - FilterHelper(bindingAttr, ref name, out _, out MemberListType listType); RuntimeEventInfo[] cache = Cache.GetEventList(listType, name); @@ -2876,10 +2868,8 @@ 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) { - if (name is null) throw new ArgumentNullException(); - FilterHelper(bindingAttr, ref name, out _, out MemberListType listType); RuntimeFieldInfo[] cache = Cache.GetFieldList(listType, name); @@ -2915,10 +2905,8 @@ public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(Dyn [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] - public override Type? GetInterface(string fullname, bool ignoreCase) + public override Type? GetInterface(string fullname!!, bool ignoreCase) { - if (fullname is null) throw new ArgumentNullException(nameof(fullname)); - BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; bindingAttr &= ~BindingFlags.Static; @@ -2950,10 +2938,8 @@ 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) { - if (fullname is null) throw new ArgumentNullException(nameof(fullname)); - bindingAttr &= ~BindingFlags.Static; string name, ns; SplitName(fullname, out name!, out ns!); @@ -2979,10 +2965,8 @@ 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) { - if (name is null) throw new ArgumentNullException(nameof(name)); - ListBuilder methods = default; ListBuilder constructors = default; ListBuilder properties = default; @@ -3061,10 +3045,8 @@ public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFla return compressMembers; } - public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member) + public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member!!) { - if (member is null) throw new ArgumentNullException(nameof(member)); - RuntimeType? runtimeType = this; while (runtimeType != null) { @@ -3217,10 +3199,8 @@ public override MethodBase? DeclaringMethod #region Hierarchy - public override bool IsSubclassOf(Type type) + public override bool IsSubclassOf(Type type!!) { - if (type is null) - throw new ArgumentNullException(nameof(type)); RuntimeType? rtType = type as RuntimeType; if (rtType == null) return false; @@ -3352,11 +3332,8 @@ 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!!) { - if (instantiation == null) - throw new ArgumentNullException(nameof(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 0ed1b70451bec5..7fd1eef4b1f4e8 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/String.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/String.CoreCLR.cs @@ -24,23 +24,13 @@ public partial class String [MethodImpl(MethodImplOptions.InternalCall)] private extern string? IsInterned(); - public static string Intern(string str) + public static string Intern(string str!!) { - if (str == null) - { - throw new ArgumentNullException(nameof(str)); - } - return str.Intern(); } - public static string? IsInterned(string str) + public static string? IsInterned(string str!!) { - if (str == null) - { - throw new ArgumentNullException(nameof(str)); - } - return str.IsInterned(); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs index d51fca9673e39c..bdb18da812f59a 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs @@ -545,10 +545,7 @@ internal static unsafe IntPtr ConvertSafeHandleToNative(SafeHandle? handle, ref throw new InvalidOperationException(SR.Interop_Marshal_SafeHandle_InvalidOperation); } - if (handle is null) - { - throw new ArgumentNullException(nameof(handle)); - } + ArgumentNullException.ThrowIfNull(handle); return StubHelpers.AddToCleanupList(ref cleanupWorkList, handle); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolBoundHandle.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolBoundHandle.cs index b188c8f8a162a9..3847cb8431f685 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolBoundHandle.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolBoundHandle.cs @@ -71,11 +71,8 @@ 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!!) { - if (handle == null) - throw new ArgumentNullException(nameof(handle)); - if (handle.IsClosed || handle.IsInvalid) throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle)); @@ -175,11 +172,8 @@ 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) { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - EnsureNotDisposed(); ThreadPoolBoundHandleOverlapped overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, preAllocated: null, flowExecutionContext); @@ -216,11 +210,8 @@ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) /// /// [CLSCompliant(false)] - public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) + public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated!!) { - if (preAllocated == null) - throw new ArgumentNullException(nameof(preAllocated)); - EnsureNotDisposed(); preAllocated.AddRef(); @@ -266,11 +257,8 @@ 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!!) { - if (overlapped == null) - throw new ArgumentNullException(nameof(overlapped)); - // Note: we explicitly allow FreeNativeOverlapped calls after the ThreadPoolBoundHandle has been Disposed. ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped); @@ -301,11 +289,8 @@ public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) /// is . /// [CLSCompliant(false)] - public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped) + public static unsafe object? GetNativeOverlappedState(NativeOverlapped* overlapped!!) { - if (overlapped == null) - throw new ArgumentNullException(nameof(overlapped)); - ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped); Debug.Assert(wrapper._boundHandle != null); return wrapper._userState; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs b/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs index 560f2e449578f1..90e43c63c28ba6 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs @@ -91,11 +91,8 @@ 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) { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - _overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, this, flowExecutionContext); } 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 09d3478bded889..c514d5ce896ae1 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,11 +125,8 @@ 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!!) { - if (obj == null) - throw new ArgumentNullException(nameof(obj)); - return IsEnteredNative(obj); } @@ -167,13 +164,8 @@ 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!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - ObjPulse(obj); } /*======================================================================== @@ -182,13 +174,8 @@ 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!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(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 908dc57b0735ba..916f10b40e541c 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -243,20 +243,14 @@ public IntPtr EventHandleIntPtr * Unpins the native Overlapped struct ====================================================================*/ [CLSCompliant(false)] - public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) + public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr!!) { - if (nativeOverlappedPtr == null) - throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped; } [CLSCompliant(false)] - public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr) + public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr!!) { - if (nativeOverlappedPtr == null) - throw new ArgumentNullException(nameof(nativeOverlappedPtr)); - OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped._overlappedData = null; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); } 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 0937ac465ce6af..de9126d1a346d7 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 @@ -351,20 +351,13 @@ 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) { - - if (waitObject == null) - throw new ArgumentNullException(nameof(waitObject)); - - if (callBack == null) - throw new ArgumentNullException(nameof(callBack)); - RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle( waitObject, new _ThreadPoolWaitOrTimerCallback(callBack, state, flowExecutionContext), @@ -552,11 +545,8 @@ public static bool BindHandle(IntPtr osHandle) } [SupportedOSPlatform("windows")] - public static bool BindHandle(SafeHandle osHandle) + public static bool BindHandle(SafeHandle osHandle!!) { - if (osHandle == null) - throw new ArgumentNullException(nameof(osHandle)); - bool ret = false; bool mustReleaseSafeHandle = false; try diff --git a/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs b/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs index 6fc6c75c9bb4b7..f77e755be77c2e 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/TypeNameParser.cs @@ -56,15 +56,13 @@ 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) { - if (typeName == null) - throw new ArgumentNullException(nameof(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 e07d90ca32211a..2a5f10d009ec91 100644 --- a/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs +++ b/src/libraries/Common/src/Extensions/NonCapturingTimer/NonCapturingTimer.cs @@ -11,13 +11,8 @@ 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 == 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/Internal/Cryptography/HashProvider.cs b/src/libraries/Common/src/Internal/Cryptography/HashProvider.cs index 97814426e84f6d..b233d28b30b740 100644 --- a/src/libraries/Common/src/Internal/Cryptography/HashProvider.cs +++ b/src/libraries/Common/src/Internal/Cryptography/HashProvider.cs @@ -12,15 +12,13 @@ namespace Internal.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) { // 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 // an invalid number of bytes read. Since our implementations of AppendHashDataCore // end up using unsafe code, we want to be sure the arguments are valid. - if (data == null) - throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) diff --git a/src/libraries/Common/src/Internal/Cryptography/SymmetricPadding.cs b/src/libraries/Common/src/Internal/Cryptography/SymmetricPadding.cs index 1a2ae3d984bd9d..70350cfdf464ca 100644 --- a/src/libraries/Common/src/Internal/Cryptography/SymmetricPadding.cs +++ b/src/libraries/Common/src/Internal/Cryptography/SymmetricPadding.cs @@ -150,7 +150,7 @@ public static bool DepaddingRequired(PaddingMode padding) public static int GetPaddingLength(ReadOnlySpan block, PaddingMode paddingMode, int blockSize) { - int padBytes = 0; + int padBytes; // See PadBlock for a description of the padding modes. switch (paddingMode) diff --git a/src/libraries/Common/src/Internal/Cryptography/UniversalCryptoTransform.cs b/src/libraries/Common/src/Internal/Cryptography/UniversalCryptoTransform.cs index bd12894e5156cd..261f0ca965b480 100644 --- a/src/libraries/Common/src/Internal/Cryptography/UniversalCryptoTransform.cs +++ b/src/libraries/Common/src/Internal/Cryptography/UniversalCryptoTransform.cs @@ -91,10 +91,8 @@ 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) { - if (inputBuffer == null) - throw new ArgumentNullException(nameof(inputBuffer)); if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset)); if (inputCount < 0) diff --git a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs index 09f7c97d302237..2d1861e4ee9c71 100644 --- a/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs +++ b/src/libraries/Common/src/Interop/FreeBSD/Interop.Process.GetProcInfo.cs @@ -34,30 +34,30 @@ internal static partial class Process // From sys/_sigset.h [StructLayout(LayoutKind.Sequential)] - internal unsafe struct sigset_t + internal unsafe struct @sigset_t { private fixed int bits[4]; } [StructLayout(LayoutKind.Sequential)] - internal struct uid_t + internal struct @uid_t { public uint id; } [StructLayout(LayoutKind.Sequential)] - internal struct gid_t + internal struct @gid_t { public uint id; } [StructLayout(LayoutKind.Sequential)] - public struct timeval + public struct @timeval { public IntPtr tv_sec; public IntPtr tv_usec; } [StructLayout(LayoutKind.Sequential)] - private struct vnode + private struct @vnode { public long tv_sec; public long tv_usec; @@ -65,7 +65,7 @@ private struct vnode // sys/resource.h [StructLayout(LayoutKind.Sequential)] - internal struct rusage + internal struct @rusage { public timeval ru_utime; /* user time used */ public timeval ru_stime; /* system time used */ @@ -87,7 +87,7 @@ internal struct rusage // From sys/user.h [StructLayout(LayoutKind.Sequential)] - public unsafe struct kinfo_proc + public unsafe struct @kinfo_proc { public int ki_structsize; /* size of this structure */ private int ki_layout; /* reserved: layout identifier */ diff --git a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs index 0f2287ce4164bd..4d4c23f6140ffe 100644 --- a/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs +++ b/src/libraries/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.ParseMapModules.cs @@ -11,7 +11,7 @@ internal static partial class Interop { - internal static partial class procfs + internal static partial class @procfs { private const string MapsFileName = "/maps"; diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libc.cs b/src/libraries/Common/src/Interop/OSX/Interop.libc.cs index 973dc0109842bb..8157ef8c9a5b1c 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libc.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libc.cs @@ -6,7 +6,7 @@ internal static partial class Interop { - internal static partial class libc + internal static partial class @libc { [StructLayout(LayoutKind.Sequential)] internal struct AttrList diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libobjc.cs b/src/libraries/Common/src/Interop/OSX/Interop.libobjc.cs index 175b8abd3d790c..c338e87bfc0635 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libobjc.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libobjc.cs @@ -6,7 +6,7 @@ internal static partial class Interop { - internal static partial class libobjc + internal static partial class @libobjc { [StructLayout(LayoutKind.Sequential)] private struct NSOperatingSystemVersion diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs b/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs index f667641d27c996..ccac9c97439596 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libproc.GetProcessInfoById.cs @@ -8,7 +8,7 @@ internal static partial class Interop { - internal static partial class libproc + internal static partial class @libproc { // Constants from sys\param.h private const int MAXCOMLEN = 16; diff --git a/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs b/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs index a51adbb79c0835..929eb9acca871e 100644 --- a/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs +++ b/src/libraries/Common/src/Interop/OSX/Interop.libproc.cs @@ -11,7 +11,7 @@ internal static partial class Interop { - internal static partial class libproc + internal static partial class @libproc { // Constants from sys\param.h private const int MAXPATHLEN = 1024; diff --git a/src/libraries/Common/src/Interop/SunOS/procfs/Interop.ProcFsStat.TryReadProcessStatusInfo.cs b/src/libraries/Common/src/Interop/SunOS/procfs/Interop.ProcFsStat.TryReadProcessStatusInfo.cs index bbfa14b3f7b12b..2a71db0aa82c9c 100644 --- a/src/libraries/Common/src/Interop/SunOS/procfs/Interop.ProcFsStat.TryReadProcessStatusInfo.cs +++ b/src/libraries/Common/src/Interop/SunOS/procfs/Interop.ProcFsStat.TryReadProcessStatusInfo.cs @@ -5,7 +5,7 @@ internal static partial class Interop { - internal static partial class procfs + internal static partial class @procfs { /// /// Attempts to get status info for the specified process ID. diff --git a/src/libraries/Common/src/Interop/Unix/libc/Interop.GetParentPid.cs b/src/libraries/Common/src/Interop/Unix/libc/Interop.GetParentPid.cs index 95b27abf158287..9e2bd72ea28ff7 100644 --- a/src/libraries/Common/src/Interop/Unix/libc/Interop.GetParentPid.cs +++ b/src/libraries/Common/src/Interop/Unix/libc/Interop.GetParentPid.cs @@ -5,7 +5,7 @@ internal static partial class Interop { - internal static partial class libc + internal static partial class @libc { [GeneratedDllImport(Libraries.Libc, EntryPoint = "getppid")] internal static partial int GetParentPid(); diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs index 8c3b6d815c169f..e0128ab0b994a8 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs @@ -348,10 +348,7 @@ internal static unsafe int InitializeSecurityContext( ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { - if (inCredentials == null) - { - throw new ArgumentNullException(nameof(inCredentials)); - } + ArgumentNullException.ThrowIfNull(inCredentials); Debug.Assert(inSecBuffers.Count <= 3); Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Count); @@ -665,10 +662,7 @@ internal static unsafe int AcceptSecurityContext( ref SecurityBuffer outSecBuffer, ref Interop.SspiCli.ContextFlags outFlags) { - if (inCredentials == null) - { - throw new ArgumentNullException(nameof(inCredentials)); - } + ArgumentNullException.ThrowIfNull(inCredentials); Debug.Assert(inSecBuffers.Count <= 3); Interop.SspiCli.SecBufferDesc inSecurityBufferDescriptor = new Interop.SspiCli.SecBufferDesc(inSecBuffers.Count); diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs index 45a8695fc69035..1fe4e47fff9f76 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeCertContextHandle.cs @@ -17,11 +17,8 @@ internal class SafeCertContextHandle : SafeCrypt32Handle public SafeCertContextHandle() { } - public SafeCertContextHandle(SafeCertContextHandle parent) + public SafeCertContextHandle(SafeCertContextHandle parent!!) { - if (parent == null) - throw new ArgumentNullException(nameof(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 4ddf9950f5cc77..f010798cda8611 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -42,13 +42,8 @@ public CodeTypeReference() ArrayElementType = null; } - public CodeTypeReference(Type type) + public CodeTypeReference(Type type!!) { - if (type == 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 ffdfa8e4a3301f..6508e0163da334 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs @@ -39,26 +39,16 @@ 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 == 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 == 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 53dd2bd7650b94..ab3a0ec42243ed 100644 --- a/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs +++ b/src/libraries/Common/src/System/Composition/Diagnostics/CompositionTrace.cs @@ -33,18 +33,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden, @@ -53,18 +43,8 @@ public static void Registration_MemberExportConventionOverridden(Type type, Memb } } - public static void Registration_MemberImportConventionOverridden(Type type, MemberInfo member) + public static void Registration_MemberImportConventionOverridden(Type type!!, MemberInfo member!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden, @@ -73,18 +53,8 @@ public static void Registration_MemberImportConventionOverridden(Type type, Memb } } - public static void Registration_OnSatisfiedImportNotificationOverridden(Type type, MemberInfo member) + public static void Registration_OnSatisfiedImportNotificationOverridden(Type type!!, MemberInfo member!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden, @@ -93,13 +63,8 @@ public static void Registration_OnSatisfiedImportNotificationOverridden(Type typ } } - public static void Registration_PartCreationConventionOverridden(Type type) + public static void Registration_PartCreationConventionOverridden(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden, @@ -108,18 +73,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice, @@ -128,13 +83,8 @@ public static void Registration_MemberImportConventionMatchedTwice(Type type, Me } } - public static void Registration_PartMetadataConventionOverridden(Type type) + public static void Registration_PartMetadataConventionOverridden(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden, @@ -143,18 +93,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - - if (constructor == 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 5e2ecc2cf50b58..705e07a75fe38c 100644 --- a/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs +++ b/src/libraries/Common/src/System/IO/ReadOnlyMemoryStream.cs @@ -188,13 +188,8 @@ 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 980ba1f5f96d75..1db9e6b48a5215 100644 --- a/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs +++ b/src/libraries/Common/src/System/IO/StreamHelpers.CopyValidation.cs @@ -7,13 +7,8 @@ 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 == 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 81210a5aac2d1d..317ca98026f1fe 100644 --- a/src/libraries/Common/src/System/IO/StringParser.cs +++ b/src/libraries/Common/src/System/IO/StringParser.cs @@ -30,12 +30,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } _buffer = buffer; _separator = separator; _skipEmpty = skipEmpty; diff --git a/src/libraries/Common/src/System/Net/RangeValidationHelpers.cs b/src/libraries/Common/src/System/Net/RangeValidationHelpers.cs index 98322b1d0df309..c1a35a525b0a0d 100644 --- a/src/libraries/Common/src/System/Net/RangeValidationHelpers.cs +++ b/src/libraries/Common/src/System/Net/RangeValidationHelpers.cs @@ -16,10 +16,7 @@ public static bool ValidateRange(int actual, int fromAllowed, int toAllowed) public static void ValidateSegment(ArraySegment segment) { // ArraySegment is not nullable. - if (segment.Array == null) - { - throw new ArgumentNullException(nameof(segment)); - } + ArgumentNullException.ThrowIfNull(segment.Array, nameof(segment)); // Length zero is explicitly allowed if (segment.Offset < 0 || segment.Count < 0 || segment.Count > (segment.Array.Length - segment.Offset)) diff --git a/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs b/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs index d074f618bf16db..1b0bec17b7273b 100644 --- a/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs +++ b/src/libraries/Common/src/System/Net/WebSockets/WebSocketValidate.cs @@ -149,13 +149,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(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 b9184070fbc8be..47d30c4bb8da45 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -43,14 +43,11 @@ public sealed partial class public #if RESOURCES_EXTENSIONS - PreserializedResourceWriter(string fileName) + PreserializedResourceWriter(string fileName!!) #else - ResourceWriter(string fileName) + ResourceWriter(string fileName!!) #endif { - if (fileName == 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); @@ -58,13 +55,11 @@ public sealed partial class public #if RESOURCES_EXTENSIONS - PreserializedResourceWriter(Stream stream) + PreserializedResourceWriter(Stream stream!!) #else - ResourceWriter(Stream stream) + ResourceWriter(Stream stream!!) #endif { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); if (!stream.CanWrite) throw new ArgumentException(SR.Argument_StreamNotWritable); @@ -76,11 +71,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); @@ -92,11 +84,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); @@ -117,11 +106,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); @@ -153,11 +139,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (_resourceList == null) throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved); 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 c9d82c02d409b4..07ac28e32f5bb5 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,13 +5,8 @@ namespace System.Security.Cryptography.Asn1 { internal partial struct AttributeAsn { - public AttributeAsn(AsnEncodedData attribute) + public AttributeAsn(AsnEncodedData attribute!!) { - if (attribute == 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 77789901f347a9..4e6b9372bb1417 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,13 +7,8 @@ namespace System.Security.Cryptography.Asn1 { internal partial struct X509ExtensionAsn { - public X509ExtensionAsn(X509Extension extension) + public X509ExtensionAsn(X509Extension extension!!) { - if (extension == 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 a563e4f4f4104d..a57b6b25504bf7 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/CngPkcs8.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/CngPkcs8.cs @@ -34,13 +34,8 @@ internal static bool IsPlatformScheme(PbeParameters pbeParameters) internal static byte[] ExportEncryptedPkcs8PrivateKey( AsymmetricAlgorithm key, ReadOnlySpan passwordBytes, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - { - throw new ArgumentNullException(nameof(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 b04ae6216f2b5d..f43bffb6ed464f 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSAAndroid.cs @@ -206,11 +206,8 @@ protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) protected override bool TryHashData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) => AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten); - public override byte[] CreateSignature(byte[] rgbHash) + public override byte[] CreateSignature(byte[] rgbHash!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - SafeDsaHandle key = GetKey(); int signatureSize = Interop.AndroidCrypto.DsaEncodedSignatureSize(key); int signatureFieldSize = Interop.AndroidCrypto.DsaSignatureFieldSize(key) * BitsPerByte; @@ -318,13 +315,8 @@ 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!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(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 f9ec1cb44be8eb..7f6c02d6bfadca 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSACng.ImportExport.cs @@ -75,11 +75,8 @@ public override void ImportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -88,13 +85,8 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -113,13 +105,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -135,13 +124,10 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 9393dc735880f4..97b29874bc709a 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSACng.SignVerify.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSACng.SignVerify.cs @@ -17,13 +17,8 @@ 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!!) { - if (rgbHash == null) - { - throw new ArgumentNullException(nameof(rgbHash)); - } - Span stackBuf = stackalloc byte[WindowsMaxQSize]; ReadOnlySpan source = AdjustHashSizeIfNecessary(rgbHash, stackBuf); @@ -73,17 +68,8 @@ protected override unsafe bool TryCreateSignatureCore( out bytesWritten); } - public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) + public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!) { - if (rgbHash == null) - { - throw new ArgumentNullException(nameof(rgbHash)); - } - if (rgbSignature == null) - { - throw new ArgumentNullException(nameof(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 8a8445fe17f5b3..26b8e6337d92de 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSAOpenSsl.cs @@ -210,11 +210,8 @@ protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) protected override bool TryHashData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) => AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten); - public override byte[] CreateSignature(byte[] rgbHash) + public override byte[] CreateSignature(byte[] rgbHash!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - SafeDsaHandle key = GetKey(); int signatureSize = Interop.Crypto.DsaEncodedSignatureSize(key); int signatureFieldSize = Interop.Crypto.DsaSignatureFieldSize(key) * BitsPerByte; @@ -323,17 +320,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!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(rgbSignature)); - return VerifySignature((ReadOnlySpan)rgbHash, (ReadOnlySpan)rgbSignature); } - public override bool VerifySignature(ReadOnlySpan hash, ReadOnlySpan signature) => VerifySignatureCore(hash, signature, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); diff --git a/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs index a804b198d51401..f43a30578f275b 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/DSASecurityTransforms.cs @@ -66,11 +66,8 @@ public override int KeySize } } - public override byte[] CreateSignature(byte[] rgbHash) + public override byte[] CreateSignature(byte[] rgbHash!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) @@ -93,13 +90,8 @@ public override byte[] CreateSignature(byte[] rgbHash) return ieeeFormatSignature; } - public override bool VerifySignature(byte[] hash, byte[] signature) + public override bool VerifySignature(byte[] hash!!, byte[] signature!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - if (signature == null) - throw new ArgumentNullException(nameof(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 dc902e555081bc..ee454e95a39e52 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroid.Derive.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroid.Derive.cs @@ -18,12 +18,11 @@ 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(); @@ -37,13 +36,12 @@ 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(); @@ -57,15 +55,8 @@ 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!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); - if (prfLabel == null) - throw new ArgumentNullException(nameof(prfLabel)); - if (prfSeed == null) - throw new ArgumentNullException(nameof(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 ed59b20f2e2828..b6573a954c8f5f 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroidPublicKey.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanAndroidPublicKey.cs @@ -11,10 +11,8 @@ internal sealed class ECDiffieHellmanAndroidPublicKey : ECDiffieHellmanPublicKey { private ECAndroid _key; - internal ECDiffieHellmanAndroidPublicKey(SafeEcKeyHandle ecKeyHandle) + internal ECDiffieHellmanAndroidPublicKey(SafeEcKeyHandle ecKeyHandle!!) { - if (ecKeyHandle == null) - throw new ArgumentNullException(nameof(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 ebe5922994637d..1799aad9771ff5 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.ImportExport.cs @@ -165,11 +165,8 @@ private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -178,13 +175,8 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -203,13 +195,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -225,13 +214,10 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 f1db21ff401e77..a33996933c6dfb 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanCng.cs @@ -71,12 +71,11 @@ 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)) @@ -91,13 +90,12 @@ 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)) @@ -116,15 +114,8 @@ public override byte[] DeriveKeyFromHmac( } } - public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) + public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey!!, byte[] prfLabel!!, byte[] prfSeed!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); - if (prfLabel == null) - throw new ArgumentNullException(nameof(prfLabel)); - if (prfSeed == null) - throw new ArgumentNullException(nameof(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 bee07782afc3d9..f31d79f5662d6b 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs @@ -15,12 +15,11 @@ 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(); @@ -34,13 +33,12 @@ 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(); @@ -54,15 +52,8 @@ 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!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); - if (prfLabel == null) - throw new ArgumentNullException(nameof(prfLabel)); - if (prfSeed == null) - throw new ArgumentNullException(nameof(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 d36370d054f9a0..192f2a435d956c 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs @@ -9,10 +9,8 @@ internal sealed class ECDiffieHellmanOpenSslPublicKey : ECDiffieHellmanPublicKey { private ECOpenSsl _key; - internal ECDiffieHellmanOpenSslPublicKey(SafeEvpPKeyHandle pkeyHandle) + internal ECDiffieHellmanOpenSslPublicKey(SafeEvpPKeyHandle pkeyHandle!!) { - if (pkeyHandle == null) - throw new ArgumentNullException(nameof(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 ff17de4523cde4..b6b8fe3dcf88ac 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanSecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanSecurityTransforms.cs @@ -121,12 +121,11 @@ 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(); @@ -140,13 +139,12 @@ 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(); @@ -160,16 +158,8 @@ 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!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); - if (prfLabel == null) - throw new ArgumentNullException(nameof(prfLabel)); - if (prfSeed == null) - throw new ArgumentNullException(nameof(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 5ed0a57162b464..f08dad9df4045f 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaAndroid.cs @@ -79,11 +79,8 @@ public override KeySizes[] LegalKeySizes } } - public override byte[] SignHash(byte[] hash) + public override byte[] SignHash(byte[] hash!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - ThrowIfDisposed(); SafeEcKeyHandle key = _key.Value; int signatureLength = Interop.AndroidCrypto.EcDsaSize(key); @@ -187,13 +184,8 @@ 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!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - if (signature == null) - throw new ArgumentNullException(nameof(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 003c6ba312f40a..867e2d93f61a8a 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.ImportExport.cs @@ -182,11 +182,8 @@ private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -195,13 +192,8 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -220,13 +212,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -242,13 +231,10 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 8ecfd35843706a..4b5102319f8f7f 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.SignVerify.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaCng.SignVerify.cs @@ -16,11 +16,8 @@ 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!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - int estimatedSize = KeySize switch { 256 => 64, @@ -87,13 +84,8 @@ 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!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - if (signature == null) - throw new ArgumentNullException(nameof(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 898fe32d37dc5d..72881df26bdd12 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaOpenSsl.cs @@ -89,11 +89,8 @@ public override KeySizes[] LegalKeySizes } } - public override byte[] SignHash(byte[] hash) + public override byte[] SignHash(byte[] hash!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - ThrowIfDisposed(); SafeEcKeyHandle key = _key.Value; int signatureLength = Interop.Crypto.EcDsaSize(key); @@ -197,13 +194,8 @@ 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!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - if (signature == null) - throw new ArgumentNullException(nameof(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 0f4bcb418c89b2..ff140bac5a8e50 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECDsaSecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECDsaSecurityTransforms.cs @@ -57,11 +57,8 @@ public override int KeySize } } - public override byte[] SignHash(byte[] hash) + public override byte[] SignHash(byte[] hash!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) @@ -111,13 +108,8 @@ public override bool TrySignHash(ReadOnlySpan source, Span destinati } } - public override bool VerifyHash(byte[] hash, byte[] signature) + public override bool VerifyHash(byte[] hash!!, byte[] signature!!) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - if (signature == null) - throw new ArgumentNullException(nameof(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 86d98f5014f6cc..2eb658db3ea3eb 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs @@ -73,13 +73,8 @@ public override KeySizes[] LegalKeySizes } } - public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) + public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(padding)); - Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor); SafeRsaHandle key = GetKey(); @@ -109,14 +104,9 @@ public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) public override bool TryDecrypt( ReadOnlySpan data, Span destination, - RSAEncryptionPadding padding, + RSAEncryptionPadding padding!!, out int bytesWritten) { - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor); SafeRsaHandle key = GetKey(); @@ -243,13 +233,8 @@ private static bool TryDecrypt( } } - public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) + public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(padding)); - Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor); SafeRsaHandle key = GetKey(); @@ -272,13 +257,8 @@ 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) { - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor); SafeRsaHandle key = GetKey(); @@ -789,20 +769,11 @@ private bool TrySignHash( } public override bool VerifyHash( - byte[] hash, - byte[] signature, + byte[] hash!!, + byte[] signature!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) - { - throw new ArgumentNullException(nameof(hash)); - } - if (signature == null) - { - throw new ArgumentNullException(nameof(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 856cf4b6f2aa21..0ff2474f0f7cee 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs @@ -34,17 +34,8 @@ 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) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); if (!encrypt && data.Length != modulusSizeInBytes) @@ -126,13 +117,8 @@ private unsafe byte[] EncryptOrDecrypt(byte[] data, RSAEncryptionPadding padding // 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) { - if (padding == null) - { - throw new ArgumentNullException(nameof(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 66206156ece89e..00db1b73074ffd 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.ImportExport.cs @@ -191,11 +191,8 @@ private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, @@ -204,13 +201,8 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (pbeParameters == null) - { - throw new ArgumentNullException(nameof(pbeParameters)); - } - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -229,13 +221,10 @@ public override byte[] ExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -251,13 +240,10 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 947a73416d7d37..b9e3a41e6171c9 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.SignVerify.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.SignVerify.cs @@ -40,13 +40,8 @@ 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) { - if (hash == null) - { - throw new ArgumentNullException(nameof(hash)); - } - string? hashAlgorithmName = hashAlgorithm.Name; ArgumentException.ThrowIfNullOrEmpty(hashAlgorithmName, nameof(hashAlgorithm)); @@ -127,17 +122,8 @@ 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) { - if (hash == null) - { - throw new ArgumentNullException(nameof(hash)); - } - if (signature == null) - { - throw new ArgumentNullException(nameof(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 e87f36e6a0d9d4..b5f1d78caac1df 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs @@ -80,13 +80,8 @@ public override KeySizes[] LegalKeySizes } } - public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) + public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(padding)); - ValidatePadding(padding); SafeEvpPKeyHandle key = GetKey(); int rsaSize = Interop.Crypto.EvpPKeySize(key); @@ -110,12 +105,9 @@ public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) public override bool TryDecrypt( ReadOnlySpan data, Span destination, - RSAEncryptionPadding padding, + RSAEncryptionPadding padding!!, out int bytesWritten) { - if (padding == null) - throw new ArgumentNullException(nameof(padding)); - ValidatePadding(padding); SafeEvpPKeyHandle key = GetKey(); int keySizeBytes = Interop.Crypto.EvpPKeySize(key); @@ -205,13 +197,8 @@ private static int Decrypt( destination); } - public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) + public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(padding)); - ValidatePadding(padding); SafeEvpPKeyHandle key = GetKey(); @@ -233,13 +220,8 @@ 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) { - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - ValidatePadding(padding); SafeEvpPKeyHandle? key = GetKey(); @@ -828,20 +810,11 @@ private bool TrySignHash( } public override bool VerifyHash( - byte[] hash, - byte[] signature, + byte[] hash!!, + byte[] signature!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) - { - throw new ArgumentNullException(nameof(hash)); - } - if (signature == null) - { - throw new ArgumentNullException(nameof(signature)); - } - return VerifyHash(new ReadOnlySpan(hash), new ReadOnlySpan(signature), hashAlgorithm, padding); } @@ -881,13 +854,8 @@ private static ReadOnlyMemory VerifyPkcs8(ReadOnlyMemory pkcs8) } } - private static void ValidatePadding(RSAEncryptionPadding padding) + private static void ValidatePadding(RSAEncryptionPadding padding!!) { - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - // There are currently two defined padding modes: // * Oaep has an option (the hash algorithm) // * Pkcs1 has no options @@ -902,13 +870,8 @@ private static void ValidatePadding(RSAEncryptionPadding padding) } } - private static void ValidatePadding(RSASignaturePadding padding) + private static void ValidatePadding(RSASignaturePadding padding!!) { - if (padding == null) - { - throw new ArgumentNullException(nameof(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 36c8e026f5d4e9..9e7f7f8f31b32a 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs @@ -207,17 +207,8 @@ 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!!) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - ThrowIfDisposed(); // The size of encrypt is always the keysize (in ceiling-bytes) @@ -234,13 +225,8 @@ 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) { - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - ThrowIfDisposed(); int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize); @@ -303,17 +289,8 @@ 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!!) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) @@ -331,13 +308,8 @@ 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) { - if (padding == null) - { - throw new ArgumentNullException(nameof(padding)); - } - SecKeyPair keys = GetKeys(); if (keys.PrivateKey == null) @@ -511,20 +483,11 @@ public override bool TrySignHash(ReadOnlySpan hash, Span destination } public override bool VerifyHash( - byte[] hash, - byte[] signature, + byte[] hash!!, + byte[] signature!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) - { - throw new ArgumentNullException(nameof(hash)); - } - if (signature == null) - { - throw new ArgumentNullException(nameof(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 24cef3e86216a8..7917f5a8a4d394 100644 --- a/src/libraries/Common/src/System/Text/DBCSDecoder.cs +++ b/src/libraries/Common/src/System/Text/DBCSDecoder.cs @@ -45,11 +45,8 @@ 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) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); - if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -94,11 +91,8 @@ 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) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -127,12 +121,9 @@ 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) { - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); - if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -158,11 +149,8 @@ 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) { - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); - if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -196,13 +184,10 @@ public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int 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) { - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); - if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -233,12 +218,10 @@ 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) { - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); 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 162cfdb3e5519e..0ee07ef3e888f4 100644 --- a/src/libraries/Common/src/System/Text/OSEncoder.cs +++ b/src/libraries/Common/src/System/Text/OSEncoder.cs @@ -25,11 +25,8 @@ 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) { - if (chars == null) - throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); - if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -73,11 +70,8 @@ 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) { - if (chars == null) - throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -101,12 +95,9 @@ 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) { - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); - if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -132,11 +123,8 @@ 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) { - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); - if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -170,13 +158,10 @@ public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int 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) { - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); - if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -207,12 +192,10 @@ 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) { - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); 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 d956fb0fc26cec..ec4af9d9baac87 100644 --- a/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs +++ b/src/libraries/Common/src/System/Text/OSEncoding.Windows.cs @@ -17,11 +17,8 @@ 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) { - if (chars == null) - throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); - if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -37,12 +34,8 @@ 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!!) { - // Validate input - if (s == null) - throw new ArgumentNullException(nameof(s)); - if (s.Length == 0) return 0; @@ -52,11 +45,8 @@ 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) { - if (s == null || bytes == null) - throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); - if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -81,11 +71,8 @@ public override unsafe int GetBytes(string s, int charIndex, int charCount, byte } } - 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) { - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); - if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -110,11 +97,8 @@ 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) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); - if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -130,11 +114,8 @@ 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) { - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); - if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); 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 3cb6e817aa614f..713ee8d0f80247 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,12 +113,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(continuation)); - } ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/BoundDispEvent.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/BoundDispEvent.cs index 354dcc7f9aaba0..7e99f2fa5fc361 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/BoundDispEvent.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/BoundDispEvent.cs @@ -78,7 +78,7 @@ private static void VerifyHandler(object handler) [RequiresUnreferencedCode(Binder.TrimmerWarning)] private object InPlaceAdd(object handler) { - Requires.NotNull(handler, nameof(handler)); + Requires.NotNull(handler); VerifyHandler(handler); ComEventsSink comEventSink = ComEventsSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, true); @@ -93,7 +93,7 @@ private object InPlaceAdd(object handler) /// The original event with handler removed. private object InPlaceSubtract(object handler) { - Requires.NotNull(handler, nameof(handler)); + Requires.NotNull(handler); VerifyHandler(handler); ComEventsSink comEventSink = ComEventsSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, false); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComBinder.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComBinder.cs index 26588e6a4093ae..584f40662185ce 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComBinder.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComBinder.cs @@ -35,8 +35,8 @@ public static bool IsComObject(object value) [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result, bool delayInvocation) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); + Requires.NotNull(binder); + Requires.NotNull(instance); if (TryGetMetaObject(ref instance)) { @@ -67,9 +67,9 @@ public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject in [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject value, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(value); if (TryGetMetaObject(ref instance)) { @@ -92,9 +92,9 @@ public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject in [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObjectInvoke(ref instance)) { @@ -117,9 +117,9 @@ public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static bool TryBindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObject(ref instance)) { @@ -142,9 +142,9 @@ public static bool TryBindInvokeMember(InvokeMemberBinder binder, DynamicMetaObj [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObjectInvoke(ref instance)) { @@ -168,10 +168,10 @@ public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject inst [RequiresUnreferencedCode(Binder.TrimmerWarning)] public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, DynamicMetaObject value, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); + Requires.NotNull(value); if (TryGetMetaObjectInvoke(ref instance)) { @@ -192,8 +192,8 @@ public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject inst /// true if operation was bound successfully; otherwise, false. public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); + Requires.NotNull(binder); + Requires.NotNull(instance); if (IsComObject(instance.Value)) { @@ -230,7 +230,7 @@ public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal static IList GetDynamicDataMemberNames(object value) { - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value); Requires.Condition(IsComObject(value), nameof(value)); return ComObject.ObjectToComObject(value).GetMemberNames(true); @@ -246,7 +246,7 @@ internal static IList GetDynamicDataMemberNames(object value) [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal static IList> GetDynamicDataMembers(object value, IEnumerable names) { - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value); Requires.Condition(IsComObject(value), nameof(value)); return ComObject.ObjectToComObject(value).GetMembers(names); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComFallbackMetaObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComFallbackMetaObject.cs index f7934b493f0abc..3d29a97e3b751c 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComFallbackMetaObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComFallbackMetaObject.cs @@ -23,31 +23,31 @@ internal ComFallbackMetaObject(Expression expression, BindingRestrictions restri public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackGetIndex(UnwrapSelf(), indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackSetIndex(UnwrapSelf(), indexes, value); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackGetMember(UnwrapSelf()); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackInvokeMember(UnwrapSelf(), args); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackSetMember(UnwrapSelf(), value); } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComMetaObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComMetaObject.cs index 7ae60b32a645e6..6e253be572d971 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComMetaObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComMetaObject.cs @@ -18,37 +18,37 @@ internal ComMetaObject(Expression expression, BindingRestrictions restrictions, public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(args.AddFirst(WrapSelf())); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(args.AddFirst(WrapSelf())); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf()); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), value); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), indexes.AddLast(value)); } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Helpers.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Helpers.cs index f55b2edd11228c..81cd6ae203e4b2 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Helpers.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/Helpers.cs @@ -3,6 +3,7 @@ using System; using System.Linq.Expressions; +using System.Runtime.CompilerServices; namespace Microsoft.CSharp.RuntimeBinder.ComInterop { @@ -33,12 +34,9 @@ internal static Expression Convert(Expression expression, Type type) internal static class Requires { [System.Diagnostics.Conditional("DEBUG")] - internal static void NotNull(object value, string paramName) + internal static void NotNull(object value, [CallerArgumentExpression("value")] string? paramName = null) { - if (value == null) - { - throw new ArgumentNullException(paramName); - } + ArgumentNullException.ThrowIfNull(value, paramName); } [System.Diagnostics.Conditional("DEBUG")] diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchMetaObject.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchMetaObject.cs index 772f3654497da6..d1c80b62c0a580 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchMetaObject.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchMetaObject.cs @@ -23,7 +23,7 @@ internal IDispatchMetaObject(Expression expression, IDispatchComObject self) Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetMemberMethod(binder.Name, out ComMethodDesc method) || _self.TryGetMemberMethodExplicit(binder.Name, out method)) @@ -40,7 +40,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetGetItem(out ComMethodDesc method)) { @@ -75,7 +75,7 @@ public override DynamicMetaObject BindGetMember(GetMemberBinder binder) ComBinder.ComGetMemberBinder comBinder = binder as ComBinder.ComGetMemberBinder; bool canReturnCallables = comBinder?._canReturnCallables ?? false; - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); // 1. Try methods if (_self.TryGetMemberMethod(binder.Name, out ComMethodDesc method)) @@ -149,7 +149,7 @@ private DynamicMetaObject BindEvent(ComEventDesc eventDesc) Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetGetItem(out ComMethodDesc getItem)) { @@ -164,7 +164,7 @@ public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMet Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetSetItem(out ComMethodDesc setItem)) { @@ -188,7 +188,7 @@ public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMet Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return // 1. Check for simple property put diff --git a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs index ab8305044ea9e9..d6b506cc1c6379 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/CacheEntryExtensions.cs @@ -30,13 +30,8 @@ public static ICacheEntry SetPriority( /// The for chaining. public static ICacheEntry AddExpirationToken( this ICacheEntry entry, - IChangeToken expirationToken) + IChangeToken expirationToken!!) { - if (expirationToken == null) - { - throw new ArgumentNullException(nameof(expirationToken)); - } - entry.ExpirationTokens.Add(expirationToken); return entry; } @@ -92,13 +87,8 @@ public static ICacheEntry SetSlidingExpiration( /// The for chaining. public static ICacheEntry RegisterPostEvictionCallback( this ICacheEntry entry, - PostEvictionDelegate callback) + PostEvictionDelegate callback!!) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } - return entry.RegisterPostEvictionCallback(callback, state: null); } @@ -111,14 +101,9 @@ public static ICacheEntry RegisterPostEvictionCallback( /// The for chaining. public static ICacheEntry RegisterPostEvictionCallback( this ICacheEntry entry, - PostEvictionDelegate callback, + PostEvictionDelegate callback!!, object? state) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } - entry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = callback, @@ -166,13 +151,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(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 562d8e224c0753..1793665d5222f6 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/DistributedCacheExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/DistributedCacheExtensions.cs @@ -20,17 +20,8 @@ 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!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - cache.Set(key, value, new DistributedCacheEntryOptions()); } @@ -43,17 +34,8 @@ 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)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - return cache.SetAsync(key, value, new DistributedCacheEntryOptions(), token); } @@ -77,16 +59,8 @@ 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) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } cache.Set(key, Encoding.UTF8.GetBytes(value), options); } @@ -114,16 +88,8 @@ public static void SetString(this IDistributedCache cache, string key, string va /// 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)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(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 ba75e799610122..b102cfc6485d47 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/MemoryCacheEntryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Abstractions/src/MemoryCacheEntryExtensions.cs @@ -49,13 +49,8 @@ public static MemoryCacheEntryOptions SetSize( /// The so that additional calls can be chained. public static MemoryCacheEntryOptions AddExpirationToken( this MemoryCacheEntryOptions options, - IChangeToken expirationToken) + IChangeToken expirationToken!!) { - if (expirationToken == null) - { - throw new ArgumentNullException(nameof(expirationToken)); - } - options.ExpirationTokens.Add(expirationToken); return options; } @@ -111,13 +106,8 @@ public static MemoryCacheEntryOptions SetSlidingExpiration( /// The so that additional calls can be chained. public static MemoryCacheEntryOptions RegisterPostEvictionCallback( this MemoryCacheEntryOptions options, - PostEvictionDelegate callback) + PostEvictionDelegate callback!!) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } - return options.RegisterPostEvictionCallback(callback, state: null); } @@ -130,14 +120,9 @@ 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) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } - options.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = callback, diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs index e9974c542c2259..d92f88aa26e673 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/CacheEntry.cs @@ -24,10 +24,10 @@ internal sealed partial class CacheEntry : ICacheEntry private object _value; private CacheEntryState _state; - internal CacheEntry(object key, MemoryCache memoryCache) + internal CacheEntry(object key!!, MemoryCache memoryCache!!) { - Key = key ?? throw new ArgumentNullException(nameof(key)); - _cache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache)); + Key = key; + _cache = memoryCache; _previous = memoryCache.TrackLinkedCacheEntries ? CacheEntryHelper.EnterScope(this) : null; _state = new CacheEntryState(CacheItemPriority.Normal); } diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs index 271c136fd2ce31..73096238128a97 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs @@ -40,18 +40,8 @@ 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!!) { - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - _options = optionsAccessor.Value; _logger = loggerFactory.CreateLogger(); @@ -204,9 +194,8 @@ internal void SetEntry(CacheEntry entry) } /// - public bool TryGetValue(object key, out object result) + public bool TryGetValue(object key!!, out object result) { - ValidateCacheKey(key); CheckDisposed(); DateTimeOffset utcNow = _options.Clock.UtcNow; @@ -246,9 +235,8 @@ public bool TryGetValue(object key, out object result) } /// - public void Remove(object key) + public void Remove(object key!!) { - ValidateCacheKey(key); CheckDisposed(); CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime @@ -497,14 +485,8 @@ private void CheckDisposed() static void Throw() => throw new ObjectDisposedException(typeof(MemoryCache).FullName); } - private static void ValidateCacheKey(object key) + private static void ValidateCacheKey(object key!!) { - if (key == null) - { - Throw(); - } - - static void Throw() => throw new ArgumentNullException(nameof(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 7fd0295cc67926..6e754b5d9c9f15 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCacheServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCacheServiceCollectionExtensions.cs @@ -19,13 +19,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); @@ -41,18 +36,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } - services.AddMemoryCache(); services.Configure(setupAction); @@ -73,13 +58,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); @@ -103,18 +83,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(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 ec8d34cb35851b..698c2b7004db0b 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs @@ -18,58 +18,23 @@ public class MemoryDistributedCache : IDistributedCache public MemoryDistributedCache(IOptions optionsAccessor) : this(optionsAccessor, NullLoggerFactory.Instance) { } - public MemoryDistributedCache(IOptions optionsAccessor, ILoggerFactory loggerFactory) + public MemoryDistributedCache(IOptions optionsAccessor!!, ILoggerFactory loggerFactory!!) { - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - _memCache = new MemoryCache(optionsAccessor.Value, loggerFactory); } - public byte[] Get(string key) + public byte[] Get(string key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return (byte[])_memCache.Get(key); } - public Task GetAsync(string key, CancellationToken token = default(CancellationToken)) + public Task GetAsync(string key!!, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return Task.FromResult(Get(key)); } - public void Set(string key, byte[] value, DistributedCacheEntryOptions options) + public void Set(string key!!, byte[] value!!, DistributedCacheEntryOptions options!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - var memoryCacheEntryOptions = new MemoryCacheEntryOptions(); memoryCacheEntryOptions.AbsoluteExpiration = options.AbsoluteExpiration; memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow; @@ -79,65 +44,30 @@ public void Set(string key, byte[] value, DistributedCacheEntryOptions options) _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)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - Set(key, value, options); return Task.CompletedTask; } - public void Refresh(string key) + public void Refresh(string key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - _memCache.TryGetValue(key, out _); } - public Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)) + public Task RefreshAsync(string key!!, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - Refresh(key); return Task.CompletedTask; } - public void Remove(string key) + public void Remove(string key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - _memCache.Remove(key); } - public Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)) + public Task RemoveAsync(string key!!, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - Remove(key); return Task.CompletedTask; } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs index 07999be0e72bc9..d10c4bdfd1bc88 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationExtensions.cs @@ -94,13 +94,8 @@ 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) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(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 814d9113c840fa..0ee4036cca37c5 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationPath.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Abstractions/src/ConfigurationPath.cs @@ -22,12 +22,8 @@ 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!!) { - if (pathSegments == null) - { - throw new ArgumentNullException(nameof(pathSegments)); - } return string.Join(KeyDelimiter, pathSegments); } @@ -36,12 +32,8 @@ 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!!) { - if (pathSegments == null) - { - throw new ArgumentNullException(nameof(pathSegments)); - } return string.Join(KeyDelimiter, pathSegments); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs index fd395abee35828..9e361370cc7bbf 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs @@ -42,13 +42,8 @@ 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) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - object? result = configuration.Get(typeof(T), configureOptions); if (result == null) { @@ -80,16 +75,11 @@ 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) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - var options = new BinderOptions(); configureOptions?.Invoke(options); return BindInstance(type, instance: null, config: configuration, options: options); @@ -121,13 +111,8 @@ 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) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - if (instance != null) { var options = new BinderOptions(); @@ -667,13 +652,8 @@ private static List GetAllProperties( options); } - private static string GetPropertyName(MemberInfo property) + private static string GetPropertyName(MemberInfo property!!) { - if (property == null) - { - throw new ArgumentNullException(nameof(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.CommandLine/src/CommandLineConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs index a41d6f541d02fe..ac17d7009fe06a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs @@ -18,9 +18,9 @@ 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) { - Args = args ?? throw new ArgumentNullException(nameof(args)); + Args = args; if (switchMappings != null) { diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs index 815905130036ab..072e398f2c7c33 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs @@ -20,14 +20,9 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - builder.Properties[FileProviderKey] = fileProvider ?? throw new ArgumentNullException(nameof(fileProvider)); + builder.Properties[FileProviderKey] = fileProvider; return builder; } @@ -36,13 +31,8 @@ public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder b /// /// The . /// The default . - public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) + public static IFileProvider GetFileProvider(this IConfigurationBuilder builder!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (builder.Properties.TryGetValue(FileProviderKey, out object? provider)) { return (IFileProvider)provider; @@ -57,18 +47,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (basePath == null) - { - throw new ArgumentNullException(nameof(basePath)); - } - return builder.SetFileProvider(new PhysicalFileProvider(basePath)); } @@ -78,13 +58,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - builder.Properties[FileLoadExceptionHandlerKey] = handler; return builder; } @@ -94,13 +69,8 @@ public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurat /// /// The . /// The . - public static Action? GetFileLoadExceptionHandler(this IConfigurationBuilder builder) + public static Action? GetFileLoadExceptionHandler(this IConfigurationBuilder builder!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(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 60811023f6b38d..a8620f0bdbe850 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs @@ -23,9 +23,9 @@ 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!!) { - Source = source ?? throw new ArgumentNullException(nameof(source)); + Source = source; if (Source.ReloadOnChange && Source.FileProvider != null) { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs index ab5442a9195757..2c3802993713e8 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs @@ -62,12 +62,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } if (string.IsNullOrEmpty(path)) { throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path)); @@ -98,13 +94,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - return builder.Add(s => s.Stream = stream); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs index bf3a83cbad4556..b49c1a8642d4ff 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs @@ -62,12 +62,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } if (string.IsNullOrEmpty(path)) { throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path)); @@ -98,13 +94,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - return builder.Add(s => s.Stream = stream); } } diff --git a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs index 0b683da9140fa6..db166c2c88d4a2 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs @@ -116,18 +116,8 @@ 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) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - UserSecretsIdAttribute? attribute = assembly.GetCustomAttribute(); if (attribute != null) { @@ -171,18 +161,8 @@ 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) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } - - if (userSecretsId == null) - { - throw new ArgumentNullException(nameof(userSecretsId)); - } - return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), optional, reloadOnChange); } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs index dde4dd82f32e3e..242d149e440c21 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElement.cs @@ -31,9 +31,9 @@ internal sealed class XmlConfigurationElement public List Attributes { get; set; } - public XmlConfigurationElement(string elementName, string name) + public XmlConfigurationElement(string elementName!!, string name) { - ElementName = elementName ?? throw new ArgumentNullException(nameof(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 a07231787a9ba6..ea9efc1c84d4c7 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementAttributeValue.cs @@ -7,10 +7,10 @@ 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) { - Attribute = attribute ?? throw new ArgumentNullException(nameof(attribute)); - Value = value ?? throw new ArgumentNullException(nameof(value)); + Attribute = attribute; + Value = value; LineNumber = lineNumber; LinePosition = linePosition; } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs index c3ef8fee108c0f..d5f5d38498937f 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationElementTextContent.cs @@ -7,9 +7,9 @@ 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) { - TextContent = textContent ?? throw new ArgumentNullException(nameof(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 8e6a9096efcfc1..24cb252ec5590d 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/XmlConfigurationExtensions.cs @@ -62,12 +62,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } if (string.IsNullOrEmpty(path)) { throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path)); @@ -98,13 +94,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(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 77d0a50a93b88e..118bacffe74a20 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedBuilderExtensions.cs @@ -27,17 +27,8 @@ 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) { - if (configurationBuilder == null) - { - throw new ArgumentNullException(nameof(configurationBuilder)); - } - if (config == null) - { - throw new ArgumentNullException(nameof(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 eb9bed00211458..f0a9380a6656e2 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -19,12 +19,8 @@ public class ChainedConfigurationProvider : IConfigurationProvider, IDisposable /// Initialize a new instance from the source configuration. /// /// The source configuration. - public ChainedConfigurationProvider(ChainedConfigurationSource source) + public ChainedConfigurationProvider(ChainedConfigurationSource source!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } if (source.Configuration == null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Configuration"), nameof(source)); diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs index d0ac712e6a09ac..c0675526e94248 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationBuilder.cs @@ -27,13 +27,8 @@ public class ConfigurationBuilder : IConfigurationBuilder /// /// The configuration source to add. /// The same . - public IConfigurationBuilder Add(IConfigurationSource source) + public IConfigurationBuilder Add(IConfigurationSource source!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(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 1fb575e0c0c0d7..8cb01120704a6f 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs @@ -80,9 +80,9 @@ public void Dispose() _providerManager.Dispose(); } - IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) + IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source!!) { - _sources.Add(source ?? throw new ArgumentNullException(nameof(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 397ef5160b1ec7..ae0e1e6bb52af5 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationRoot.cs @@ -21,13 +21,8 @@ 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!!) { - if (providers == null) - { - throw new ArgumentNullException(nameof(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 0896e587d4082d..35996f15afec13 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationSection.cs @@ -21,18 +21,8 @@ public class ConfigurationSection : IConfigurationSection /// /// The configuration root. /// The path to this section. - public ConfigurationSection(IConfigurationRoot root, string path) + public ConfigurationSection(IConfigurationRoot root!!, string path!!) { - if (root == null) - { - throw new ArgumentNullException(nameof(root)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(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 15ed46a26a5b98..781d37effe0456 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationBuilderExtensions.cs @@ -17,13 +17,8 @@ public static class MemoryConfigurationBuilderExtensions /// /// The to add to. /// The . - public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder) + public static IConfigurationBuilder AddInMemoryCollection(this IConfigurationBuilder configurationBuilder!!) { - if (configurationBuilder == null) - { - throw new ArgumentNullException(nameof(configurationBuilder)); - } - configurationBuilder.Add(new MemoryConfigurationSource()); return configurationBuilder; } @@ -35,14 +30,9 @@ 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) { - if (configurationBuilder == null) - { - throw new ArgumentNullException(nameof(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 0e7f0be02fec78..1e2c17fb6e764c 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/MemoryConfigurationProvider.cs @@ -18,13 +18,8 @@ public class MemoryConfigurationProvider : ConfigurationProvider, IEnumerable /// The source settings. - public MemoryConfigurationProvider(MemoryConfigurationSource source) + public MemoryConfigurationProvider(MemoryConfigurationSource source!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - _source = source; if (_source.InitialData != null) diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs index 6d8917a188fd65..8d6b4b3866cb92 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/StreamConfigurationProvider.cs @@ -22,9 +22,9 @@ public abstract class StreamConfigurationProvider : ConfigurationProvider /// Constructor. /// /// The source. - public StreamConfigurationProvider(StreamConfigurationSource source) + public StreamConfigurationProvider(StreamConfigurationSource source!!) { - Source = source ?? throw new ArgumentNullException(nameof(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 6057a9b87a7861..9f0f7b380a17b0 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/AsyncServiceScope.cs @@ -18,9 +18,9 @@ namespace Microsoft.Extensions.DependencyInjection /// Wraps an instance of . /// /// The instance to wrap. - public AsyncServiceScope(IServiceScope serviceScope) + public AsyncServiceScope(IServiceScope serviceScope!!) { - _serviceScope = serviceScope ?? throw new ArgumentNullException(nameof(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 e4cfae88c17e06..7ec5f7c4913ef0 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Extensions/ServiceCollectionDescriptorExtensions.cs @@ -19,19 +19,9 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } - collection.Add(descriptor); return collection; } @@ -43,19 +33,9 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (descriptors == null) - { - throw new ArgumentNullException(nameof(descriptors)); - } - foreach (ServiceDescriptor? descriptor in descriptors) { collection.Add(descriptor); @@ -71,19 +51,9 @@ public static IServiceCollection Add( /// The . /// The to add. public static void TryAdd( - this IServiceCollection collection, - ServiceDescriptor descriptor) + this IServiceCollection collection!!, + ServiceDescriptor descriptor!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } - int count = collection.Count; for (int i = 0; i < count; i++) { @@ -104,19 +74,9 @@ public static void TryAdd( /// The . /// The s to add. public static void TryAdd( - this IServiceCollection collection, - IEnumerable descriptors) + this IServiceCollection collection!!, + IEnumerable descriptors!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (descriptors == null) - { - throw new ArgumentNullException(nameof(descriptors)); - } - foreach (ServiceDescriptor? d in descriptors) { collection.TryAdd(d); @@ -130,19 +90,9 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - var descriptor = ServiceDescriptor.Transient(service, service); TryAdd(collection, descriptor); } @@ -156,25 +106,10 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - var descriptor = ServiceDescriptor.Transient(service, implementationType); TryAdd(collection, descriptor); } @@ -188,25 +123,10 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - var descriptor = ServiceDescriptor.Transient(service, implementationFactory); TryAdd(collection, descriptor); } @@ -217,14 +137,9 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - TryAddTransient(collection, typeof(TService), typeof(TService)); } @@ -236,15 +151,10 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - TryAddTransient(collection, typeof(TService), typeof(TImplementation)); } @@ -271,19 +181,9 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - var descriptor = ServiceDescriptor.Scoped(service, service); TryAdd(collection, descriptor); } @@ -297,25 +197,10 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - var descriptor = ServiceDescriptor.Scoped(service, implementationType); TryAdd(collection, descriptor); } @@ -329,25 +214,10 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - var descriptor = ServiceDescriptor.Scoped(service, implementationFactory); TryAdd(collection, descriptor); } @@ -358,14 +228,9 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - TryAddScoped(collection, typeof(TService), typeof(TService)); } @@ -377,15 +242,10 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - TryAddScoped(collection, typeof(TService), typeof(TImplementation)); } @@ -412,19 +272,9 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - var descriptor = ServiceDescriptor.Singleton(service, service); TryAdd(collection, descriptor); } @@ -438,25 +288,10 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - var descriptor = ServiceDescriptor.Singleton(service, implementationType); TryAdd(collection, descriptor); } @@ -470,25 +305,10 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - var descriptor = ServiceDescriptor.Singleton(service, implementationFactory); TryAdd(collection, descriptor); } @@ -499,14 +319,9 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - TryAddSingleton(collection, typeof(TService), typeof(TService)); } @@ -518,15 +333,10 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - TryAddSingleton(collection, typeof(TService), typeof(TImplementation)); } @@ -538,19 +348,9 @@ 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 { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - var descriptor = ServiceDescriptor.Singleton(typeof(TService), instance); TryAdd(collection, descriptor); } @@ -589,19 +389,9 @@ public static void TryAddSingleton( /// of multiple implementation types. /// public static void TryAddEnumerable( - this IServiceCollection services, - ServiceDescriptor descriptor) + this IServiceCollection services!!, + ServiceDescriptor descriptor!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } - Type? implementationType = descriptor.GetImplementationType(); if (implementationType == typeof(object) || @@ -647,19 +437,9 @@ public static void TryAddEnumerable( /// of multiple implementation types. /// public static void TryAddEnumerable( - this IServiceCollection services, - IEnumerable descriptors) + this IServiceCollection services!!, + IEnumerable descriptors!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (descriptors == null) - { - throw new ArgumentNullException(nameof(descriptors)); - } - foreach (ServiceDescriptor? d in descriptors) { services.TryAddEnumerable(d); @@ -674,19 +454,9 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (descriptor == null) - { - throw new ArgumentNullException(nameof(descriptor)); - } - // Remove existing int count = collection.Count; for (int i = 0; i < count; i++) @@ -718,13 +488,8 @@ 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!!) { - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - for (int i = collection.Count - 1; i >= 0; i--) { ServiceDescriptor? descriptor = collection[i]; diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs index 1de2b83d156f0c..39069984887bfe 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceCollectionServiceExtensions.cs @@ -22,25 +22,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - return Add(services, serviceType, implementationType, ServiceLifetime.Transient); } @@ -55,25 +40,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient); } @@ -87,15 +57,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - return services.AddTransient(typeof(TService), typeof(TImplementation)); } @@ -108,19 +73,9 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - return services.AddTransient(serviceType, serviceType); } @@ -132,14 +87,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - return services.AddTransient(typeof(TService)); } @@ -154,20 +104,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return services.AddTransient(typeof(TService), implementationFactory); } @@ -184,21 +124,11 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return services.AddTransient(typeof(TService), implementationFactory); } @@ -213,25 +143,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - return Add(services, serviceType, implementationType, ServiceLifetime.Scoped); } @@ -246,25 +161,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped); } @@ -278,15 +178,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - return services.AddScoped(typeof(TService), typeof(TImplementation)); } @@ -299,19 +194,9 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - return services.AddScoped(serviceType, serviceType); } @@ -323,14 +208,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - return services.AddScoped(typeof(TService)); } @@ -345,20 +225,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return services.AddScoped(typeof(TService), implementationFactory); } @@ -375,21 +245,11 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return services.AddScoped(typeof(TService), implementationFactory); } @@ -405,25 +265,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - return Add(services, serviceType, implementationType, ServiceLifetime.Singleton); } @@ -438,25 +283,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton); } @@ -470,15 +300,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - return services.AddSingleton(typeof(TService), typeof(TImplementation)); } @@ -491,19 +316,9 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - return services.AddSingleton(serviceType, serviceType); } @@ -515,14 +330,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - return services.AddSingleton(typeof(TService)); } @@ -537,20 +347,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return services.AddSingleton(typeof(TService), implementationFactory); } @@ -567,21 +367,11 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return services.AddSingleton(typeof(TService), implementationFactory); } @@ -596,25 +386,10 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationInstance == null) - { - throw new ArgumentNullException(nameof(implementationInstance)); - } - var serviceDescriptor = new ServiceDescriptor(serviceType, implementationInstance); services.Add(serviceDescriptor); return services; @@ -630,20 +405,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (implementationInstance == null) - { - throw new ArgumentNullException(nameof(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 57a6d8d33f7d7d..4c98834539fe62 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs @@ -20,21 +20,11 @@ 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) { - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - ImplementationType = implementationType; } @@ -45,20 +35,10 @@ 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) { - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - ImplementationInstance = instance; } @@ -69,21 +49,11 @@ 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) { - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - ImplementationFactory = factory; } @@ -169,19 +139,9 @@ 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!!) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - return Describe(service, implementationType, ServiceLifetime.Transient); } @@ -196,15 +156,10 @@ 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 { - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } @@ -216,14 +171,9 @@ 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 { - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient); } @@ -235,18 +185,8 @@ 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!!) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(service, implementationFactory, ServiceLifetime.Transient); } @@ -291,15 +231,10 @@ 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 { - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } @@ -311,14 +246,9 @@ 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 { - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped); } @@ -330,18 +260,8 @@ 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!!) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(service, implementationFactory, ServiceLifetime.Scoped); } @@ -369,19 +289,9 @@ 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!!) { - if (service == null) - { - throw new ArgumentNullException(nameof(service)); - } - - if (implementationType == null) - { - throw new ArgumentNullException(nameof(implementationType)); - } - return Describe(service, implementationType, ServiceLifetime.Singleton); } @@ -396,15 +306,10 @@ 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 { - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } @@ -416,14 +321,9 @@ 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 { - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton); } @@ -436,19 +336,9 @@ 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!!) { - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationFactory == null) - { - throw new ArgumentNullException(nameof(implementationFactory)); - } - return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton); } @@ -460,14 +350,9 @@ 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 { - if (implementationInstance == null) - { - throw new ArgumentNullException(nameof(implementationInstance)); - } - return Singleton(typeof(TService), implementationInstance); } @@ -480,19 +365,9 @@ 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!!) { - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - - if (implementationInstance == null) - { - throw new ArgumentNullException(nameof(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 05388865bec599..048c1b0cfe467e 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceProviderServiceExtensions.cs @@ -18,13 +18,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - return (T?)provider.GetService(typeof(T)); } @@ -35,18 +30,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } - if (provider is ISupportRequiredService requiredServiceSupportingProvider) { return requiredServiceSupportingProvider.GetRequiredService(serviceType); @@ -68,13 +53,8 @@ public static object GetRequiredService(this IServiceProvider provider, Type ser /// 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 { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - return (T)provider.GetRequiredService(typeof(T)); } @@ -84,13 +64,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - return provider.GetRequiredService>(); } @@ -100,18 +75,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (serviceType == null) - { - throw new ArgumentNullException(nameof(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 ac35609032f6a8..67c641096a420a 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/DefaultServiceProviderFactory.cs @@ -26,13 +26,8 @@ public DefaultServiceProviderFactory() : this(ServiceProviderOptions.Default) /// with the specified . /// /// The options to use for this instance. - public DefaultServiceProviderFactory(ServiceProviderOptions options) + public DefaultServiceProviderFactory(ServiceProviderOptions options!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - _options = options; } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs index ce4dd0cb8943ec..2a4b1c2f0dd401 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceCollectionContainerBuilderExtensions.cs @@ -46,18 +46,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (options == 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 a4092ca70c83ae..db2701be21ae0c 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs @@ -529,13 +529,8 @@ 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 8071c67013352d..851b90a8a011ee 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 ?? throw new ArgumentNullException(nameof(serviceType)); + _serviceType = 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 fd49bff68e1a99..8785e36d6849e1 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/CompilationLibrary.cs @@ -25,17 +25,13 @@ 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) { - if (assemblies == null) - { - throw new ArgumentNullException(nameof(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 676e8a3a88d4f9..2ac677537aceef 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,10 +60,6 @@ public CompilationOptions(IEnumerable defines, bool? emitEntryPoint, bool? generateXmlDocumentation) { - if (defines == null) - { - throw new ArgumentNullException(nameof(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 39a6d80a5f0343..9eff25c3064dad 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContext.cs @@ -16,33 +16,12 @@ 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!!) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - if (compilationOptions == null) - { - throw new ArgumentNullException(nameof(compilationOptions)); - } - if (compileLibraries == null) - { - throw new ArgumentNullException(nameof(compileLibraries)); - } - if (runtimeLibraries == null) - { - throw new ArgumentNullException(nameof(runtimeLibraries)); - } - if (runtimeGraph == null) - { - throw new ArgumentNullException(nameof(runtimeGraph)); - } - Target = target; CompilationOptions = compilationOptions; CompileLibraries = compileLibraries.ToArray(); @@ -63,13 +42,8 @@ public DependencyContext(TargetInfo target, public IReadOnlyList RuntimeGraph { get; } - public DependencyContext Merge(DependencyContext other) + public DependencyContext Merge(DependencyContext other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(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 ee9f0be63e5b82..6b77fd4ec34a54 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextExtensions.cs @@ -13,151 +13,63 @@ public static class DependencyContextExtensions { private const string NativeImageSufix = ".ni"; - public static IEnumerable GetDefaultNativeAssets(this DependencyContext self) + public static IEnumerable GetDefaultNativeAssets(this DependencyContext self!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } return self.RuntimeLibraries.SelectMany(library => library.GetDefaultNativeAssets(self)); } - public static IEnumerable GetDefaultNativeRuntimeFileAssets(this DependencyContext self) + public static IEnumerable GetDefaultNativeRuntimeFileAssets(this DependencyContext self!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (runtimeIdentifier == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (runtimeIdentifier == null) - { - throw new ArgumentNullException(nameof(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) { - if (self == null) - { - throw new ArgumentNullException(nameof(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) { - if (self == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (runtimeIdentifier == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (runtimeIdentifier == null) - { - throw new ArgumentNullException(nameof(runtimeIdentifier)); - } return ResolveRuntimeFiles(context, runtimeIdentifier, self.NativeLibraryGroups); } - public static IEnumerable GetDefaultAssemblyNames(this DependencyContext self) + public static IEnumerable GetDefaultAssemblyNames(this DependencyContext self!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (runtimeIdentifier == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (context == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (self == null) - { - throw new ArgumentNullException(nameof(self)); - } - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (runtimeIdentifier == null) - { - throw new ArgumentNullException(nameof(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 e4b26591038502..fb3e4faeccf70d 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextJsonReader.cs @@ -19,13 +19,8 @@ public class DependencyContextJsonReader : IDependencyContextReader private readonly IDictionary _stringPool = new Dictionary(); - public DependencyContext Read(Stream stream) + public DependencyContext Read(Stream stream!!) { - if (stream == null) - { - throw new ArgumentNullException(nameof(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 2249ff69d87056..087db03c039afa 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextLoader.cs @@ -52,13 +52,8 @@ 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!!) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(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 77199168537287..0fb34c4db048bd 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs @@ -13,17 +13,8 @@ namespace Microsoft.Extensions.DependencyModel { public class DependencyContextWriter { - public void Write(DependencyContext context, Stream stream) + public void Write(DependencyContext context!!, Stream stream!!) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (stream == null) - { - throw new ArgumentNullException(nameof(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/Resolution/AppBaseCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs index e6d99ea4aec7ae..c190e658b6fc95 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs @@ -30,20 +30,15 @@ internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem) { } - internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem, string basePath, DependencyContextPaths dependencyContextPaths) + internal AppBaseCompilationAssemblyResolver(IFileSystem fileSystem!!, string basePath!!, DependencyContextPaths dependencyContextPaths!!) { - _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - _basePath = basePath ?? throw new ArgumentNullException(nameof(basePath)); - _dependencyContextPaths = dependencyContextPaths ?? throw new ArgumentNullException(nameof(dependencyContextPaths)); + _fileSystem = fileSystem; + _basePath = basePath; + _dependencyContextPaths = dependencyContextPaths; } - public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) + public bool TryResolveAssemblyPaths(CompilationLibrary library!!, List? assemblies) { - if (library is null) - { - throw new ArgumentNullException(nameof(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 fb758d084e9777..469afe37fd2022 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/CompositeCompilationAssemblyResolver.cs @@ -10,9 +10,9 @@ public class CompositeCompilationAssemblyResolver: ICompilationAssemblyResolver { private readonly ICompilationAssemblyResolver[] _resolvers; - public CompositeCompilationAssemblyResolver(ICompilationAssemblyResolver[] resolvers) + public CompositeCompilationAssemblyResolver(ICompilationAssemblyResolver[] resolvers!!) { - _resolvers = resolvers ?? throw new ArgumentNullException(nameof(resolvers)); + _resolvers = resolvers; } public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs index efb8cf12b91d6d..b7966379e2b336 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/PackageCompilationAssemblyResolver.cs @@ -29,10 +29,10 @@ internal PackageCompilationAssemblyResolver(IEnvironment environment, { } - internal PackageCompilationAssemblyResolver(IFileSystem fileSystem, string[] nugetPackageDirectories) + internal PackageCompilationAssemblyResolver(IFileSystem fileSystem!!, string[] nugetPackageDirectories!!) { - _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - _nugetPackageDirectories = nugetPackageDirectories ?? throw new ArgumentNullException(nameof(nugetPackageDirectories)); + _fileSystem = fileSystem; + _nugetPackageDirectories = nugetPackageDirectories; } internal static string[] GetDefaultProbeDirectories(IEnvironment environment) @@ -71,13 +71,8 @@ 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) { - if (library is null) - { - throw new ArgumentNullException(nameof(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 39ccb9bf228fa4..c1e04a419e0937 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/ReferenceAssemblyPathResolver.cs @@ -31,20 +31,15 @@ internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, IEnvironment envi { } - internal ReferenceAssemblyPathResolver(IFileSystem fileSystem, string? defaultReferenceAssembliesPath, string[] fallbackSearchPaths) + internal ReferenceAssemblyPathResolver(IFileSystem fileSystem!!, string? defaultReferenceAssembliesPath, string[] fallbackSearchPaths!!) { - _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + _fileSystem = fileSystem; _defaultReferenceAssembliesPath = defaultReferenceAssembliesPath; - _fallbackSearchPaths = fallbackSearchPaths ?? throw new ArgumentNullException(nameof(fallbackSearchPaths)); + _fallbackSearchPaths = fallbackSearchPaths; } - public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) + public bool TryResolveAssemblyPaths(CompilationLibrary library!!, List? assemblies) { - if (library is null) - { - throw new ArgumentNullException(nameof(library)); - } - if (!string.Equals(library.Type, "referenceassembly", StringComparison.OrdinalIgnoreCase)) { return false; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeLibrary.cs index 1b03ce8a181da8..74e97f2895729f 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,18 +105,6 @@ public RuntimeLibrary(string type, hashPath, runtimeStoreManifestName) { - if (runtimeAssemblyGroups == null) - { - throw new ArgumentNullException(nameof(runtimeAssemblyGroups)); - } - if (nativeLibraryGroups == null) - { - throw new ArgumentNullException(nameof(nativeLibraryGroups)); - } - if (resourceAssemblies == null) - { - throw new ArgumentNullException(nameof(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 3d7b73f3e334d0..653b76e1f2e6a7 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeDirectoryContents.cs @@ -25,12 +25,8 @@ 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) { - if (fileProviders == null) - { - throw new ArgumentNullException(nameof(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 4f2ef8f406d014..c231b57098c60e 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Composite/src/CompositeFileProvider.cs @@ -29,12 +29,8 @@ 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!!) { - if (fileProviders == null) - { - throw new ArgumentNullException(nameof(fileProviders)); - } _fileProviders = fileProviders.ToArray(); } 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 3fa750bb407651..b78b9f5bb78044 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/Internal/PhysicalDirectoryContents.cs @@ -33,9 +33,9 @@ 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) { - _directory = directory ?? throw new ArgumentNullException(nameof(directory)); + _directory = directory; _filters = filters; } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs index 312e600b05399f..9e99d2576c2c07 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs @@ -131,13 +131,8 @@ 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!!) { - if (filter == null) - { - throw new ArgumentNullException(nameof(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 3967a31da9c265..e02eb2da05374a 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Abstractions/FileInfoWrapper.cs @@ -17,9 +17,9 @@ public class FileInfoWrapper : FileInfoBase /// Initializes instance of to wrap the specified object . /// /// The - public FileInfoWrapper(FileInfo fileInfo) + public FileInfoWrapper(FileInfo fileInfo!!) { - _fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo)); + _fileInfo = fileInfo; } /// diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs index 79390d6fd6bffb..9e8e1416e41d37 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/FilePatternMatch.cs @@ -35,9 +35,9 @@ 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) { - Path = path ?? throw new ArgumentNullException(nameof(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 d5f69305ced259..490c5bec25354a 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/LiteralPathSegment.cs @@ -13,10 +13,9 @@ public class LiteralPathSegment : IPathSegment public bool CanProduceStem => false; - public LiteralPathSegment(string value, StringComparison comparisonType) + public LiteralPathSegment(string value!!, StringComparison comparisonType) { - Value = value ?? throw new ArgumentNullException(nameof(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 a8de519f761a26..5f925b2d83f9b5 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PathSegments/WildcardPathSegment.cs @@ -15,11 +15,11 @@ 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) { - BeginsWith = beginsWith ?? throw new ArgumentNullException(nameof(beginsWith)); - Contains = contains ?? throw new ArgumentNullException(nameof(contains)); - EndsWith = endsWith ?? throw new ArgumentNullException(nameof(endsWith)); + BeginsWith = beginsWith; + Contains = contains; + EndsWith = endsWith; _comparisonType = comparisonType; } 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 b03621d46aa685..de726bbb7793c8 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextLinear.cs @@ -10,9 +10,9 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts public abstract class PatternContextLinear : PatternContext { - public PatternContextLinear(ILinearPattern pattern) + public PatternContextLinear(ILinearPattern pattern!!) { - Pattern = pattern ?? throw new ArgumentNullException(nameof(pattern)); + Pattern = pattern; } public override PatternTestResult Test(FileInfoBase file) 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 06df2db3b968e0..bbce5625337db3 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContextRagged.cs @@ -9,9 +9,9 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts { public abstract class PatternContextRagged : PatternContext { - public PatternContextRagged(IRaggedPattern pattern) + public PatternContextRagged(IRaggedPattern pattern!!) { - Pattern = pattern ?? throw new ArgumentNullException(nameof(pattern)); + Pattern = pattern; } public override PatternTestResult Test(FileInfoBase file) 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 eca50420795bb5..f519150c450411 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/Patterns/PatternBuilder.cs @@ -25,13 +25,8 @@ public PatternBuilder(StringComparison comparisonType) public StringComparison ComparisonType { get; } - public IPattern Build(string pattern) + public IPattern Build(string pattern!!) { - if (pattern == null) - { - throw new ArgumentNullException(nameof(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 e87333e109b4e3..f298d001f8906e 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Matcher.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Matcher.cs @@ -160,13 +160,8 @@ 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!!) { - if (directoryInfo is null) - { - throw new ArgumentNullException(nameof(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 91204a08f6a70b..4c2ab4ac04e9de 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/MatcherExtensions.cs @@ -98,13 +98,8 @@ 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) { - if (matcher == null) - { - throw new ArgumentNullException(nameof(matcher)); - } - return matcher.Execute(new InMemoryDirectoryInfo(rootDir, files)); } } diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs index c907984daa6f52..e0536ece0c315d 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/PatternMatchingResult.cs @@ -27,9 +27,9 @@ 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) { - Files = files ?? throw new ArgumentNullException(nameof(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 4caa38a5dc1edc..94ae0c004fd659 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostBuilderContext.cs @@ -11,9 +11,9 @@ namespace Microsoft.Extensions.Hosting /// public class HostBuilderContext { - public HostBuilderContext(IDictionary properties) + public HostBuilderContext(IDictionary properties!!) { - Properties = properties ?? throw new System.ArgumentNullException(nameof(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 f51299ad154194..e722f2ddb812be 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostEnvironmentEnvExtensions.cs @@ -15,13 +15,8 @@ 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!!) { - if (hostEnvironment == null) - { - throw new ArgumentNullException(nameof(hostEnvironment)); - } - return hostEnvironment.IsEnvironment(Environments.Development); } @@ -30,13 +25,8 @@ 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!!) { - if (hostEnvironment == null) - { - throw new ArgumentNullException(nameof(hostEnvironment)); - } - return hostEnvironment.IsEnvironment(Environments.Staging); } @@ -45,13 +35,8 @@ 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!!) { - if (hostEnvironment == null) - { - throw new ArgumentNullException(nameof(hostEnvironment)); - } - return hostEnvironment.IsEnvironment(Environments.Production); } @@ -62,14 +47,9 @@ 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) { - if (hostEnvironment == null) - { - throw new ArgumentNullException(nameof(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 e34f2b140ef33f..8871b3d20cb1bb 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/HostingEnvironmentExtensions.cs @@ -16,13 +16,8 @@ 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!!) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - return hostingEnvironment.IsEnvironment(EnvironmentName.Development); } @@ -31,13 +26,8 @@ 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!!) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - return hostingEnvironment.IsEnvironment(EnvironmentName.Staging); } @@ -46,13 +36,8 @@ 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!!) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - return hostingEnvironment.IsEnvironment(EnvironmentName.Production); } @@ -63,14 +48,9 @@ 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) { - if (hostingEnvironment == null) - { - throw new ArgumentNullException(nameof(hostingEnvironment)); - } - return string.Equals( hostingEnvironment.EnvironmentName, environmentName, diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs index 9f6aea155fff24..af166430ad4be8 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/SystemdLifetime.cs @@ -19,11 +19,11 @@ 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) { - Environment = environment ?? throw new ArgumentNullException(nameof(environment)); - ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime)); - SystemdNotifier = systemdNotifier ?? throw new ArgumentNullException(nameof(systemdNotifier)); + Environment = environment; + ApplicationLifetime = applicationLifetime; + SystemdNotifier = systemdNotifier; Logger = loggerFactory.CreateLogger("Microsoft.Hosting.Lifetime"); } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs index 5f0ad5f68d5244..98d25d625e32f2 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs @@ -46,9 +46,9 @@ 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!!) { - _configureHostConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); + _configureHostConfigActions.Add(configureDelegate); return this; } @@ -60,9 +60,9 @@ 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!!) { - _configureAppConfigActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); + _configureAppConfigActions.Add(configureDelegate); return this; } @@ -72,9 +72,9 @@ 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!!) { - _configureServicesActions.Add(configureDelegate ?? throw new ArgumentNullException(nameof(configureDelegate))); + _configureServicesActions.Add(configureDelegate); return this; } @@ -84,9 +84,9 @@ 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) + public IHostBuilder UseServiceProviderFactory(IServiceProviderFactory factory!!) { - _serviceProviderFactory = new ServiceFactoryAdapter(factory ?? throw new ArgumentNullException(nameof(factory))); + _serviceProviderFactory = new ServiceFactoryAdapter(factory); return this; } @@ -96,9 +96,9 @@ 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) + public IHostBuilder UseServiceProviderFactory(Func> factory!!) { - _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostBuilderContext, factory ?? throw new ArgumentNullException(nameof(factory))); + _serviceProviderFactory = new ServiceFactoryAdapter(() => _hostBuilderContext, factory); return this; } @@ -110,10 +110,9 @@ 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!!) { - _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate - ?? throw new ArgumentNullException(nameof(configureDelegate)))); + _configureContainerActions.Add(new ConfigureContainerAdapter(configureDelegate)); return this; } diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs index 13f7fc3f112b51..a1e8efdaf9447b 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs @@ -9,9 +9,9 @@ internal sealed class ConfigureContainerAdapter : IConfigureC { private Action _action; - public ConfigureContainerAdapter(Action action) + public ConfigureContainerAdapter(Action action!!) { - _action = action ?? throw new ArgumentNullException(nameof(action)); + _action = action; } public void ConfigureContainer(HostBuilderContext hostContext, object containerBuilder) diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs index fc738ef0bb5e98..c75eca2944f62b 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs @@ -12,15 +12,15 @@ internal sealed class ServiceFactoryAdapter : IServiceFactory private readonly Func _contextResolver; private Func> _factoryResolver; - public ServiceFactoryAdapter(IServiceProviderFactory serviceProviderFactory) + public ServiceFactoryAdapter(IServiceProviderFactory serviceProviderFactory!!) { - _serviceProviderFactory = serviceProviderFactory ?? throw new ArgumentNullException(nameof(serviceProviderFactory)); + _serviceProviderFactory = serviceProviderFactory; } - public ServiceFactoryAdapter(Func contextResolver, Func> factoryResolver) + public ServiceFactoryAdapter(Func contextResolver!!, Func> factoryResolver!!) { - _contextResolver = contextResolver ?? throw new ArgumentNullException(nameof(contextResolver)); - _factoryResolver = factoryResolver ?? throw new ArgumentNullException(nameof(factoryResolver)); + _contextResolver = contextResolver; + _factoryResolver = factoryResolver; } public object CreateBuilder(IServiceCollection services) diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs b/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs index d24d54235e6991..a8e8f064fd8463 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.cs @@ -20,14 +20,9 @@ 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 { - if (optionsBuilder == null) - { - throw new ArgumentNullException(nameof(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 059111a2e66b27..943a68ebf6ab9a 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs @@ -59,37 +59,12 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (scopeFactory == null) - { - throw new ArgumentNullException(nameof(scopeFactory)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (optionsMonitor == null) - { - throw new ArgumentNullException(nameof(optionsMonitor)); - } - - if (filters == null) - { - throw new ArgumentNullException(nameof(filters)); - } - _services = services; _scopeFactory = scopeFactory; _optionsMonitor = optionsMonitor; @@ -114,13 +89,8 @@ public DefaultHttpClientFactory( _cleanupActiveLock = new object(); } - public HttpClient CreateClient(string name) + public HttpClient CreateClient(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - HttpMessageHandler handler = CreateHandler(name); var client = new HttpClient(handler, disposeHandler: false); @@ -133,13 +103,8 @@ public HttpClient CreateClient(string name) return client; } - public HttpMessageHandler CreateHandler(string name) + public HttpMessageHandler CreateHandler(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - ActiveHandlerTrackingEntry entry = _activeHandlers.GetOrAdd(name, _entryFactory).Value; StartHandlerEntryTimer(entry); diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs index 02215b040042f0..4b913fc8d4dc97 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs @@ -15,29 +15,14 @@ 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) { - if (cache == null) - { - throw new ArgumentNullException(nameof(cache)); - } - - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - _cache = cache; _services = services; } - public TClient CreateClient(HttpClient httpClient) + public TClient CreateClient(HttpClient httpClient!!) { - if (httpClient == null) - { - throw new ArgumentNullException(nameof(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 a7d428b469d742..8162d9af2ec840 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientBuilderExtensions.cs @@ -24,18 +24,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - builder.Services.Configure(builder.Name, options => options.HttpClientActions.Add(configureClient)); return builder; @@ -51,18 +41,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - builder.Services.AddTransient>(services => { return new ConfigureNamedOptions(builder.Name, (options) => @@ -84,18 +64,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureHandler == null) - { - throw new ArgumentNullException(nameof(configureHandler)); - } - builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.AdditionalHandlers.Add(configureHandler())); @@ -119,18 +89,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureHandler == null) - { - throw new ArgumentNullException(nameof(configureHandler)); - } - builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.AdditionalHandlers.Add(configureHandler(b.Services))); @@ -153,14 +113,9 @@ 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 { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.AdditionalHandlers.Add(b.Services.GetRequiredService())); @@ -180,18 +135,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureHandler == null) - { - throw new ArgumentNullException(nameof(configureHandler)); - } - builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.PrimaryHandler = configureHandler()); @@ -217,18 +162,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureHandler == null) - { - throw new ArgumentNullException(nameof(configureHandler)); - } - builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.PrimaryHandler = configureHandler(b.Services)); @@ -252,14 +187,9 @@ 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 { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - builder.Services.Configure(builder.Name, options => { options.HttpMessageHandlerBuilderActions.Add(b => b.PrimaryHandler = b.Services.GetRequiredService()); @@ -275,18 +205,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (configureBuilder == null) - { - throw new ArgumentNullException(nameof(configureBuilder)); - } - builder.Services.Configure(builder.Name, options => options.HttpMessageHandlerBuilderActions.Add(configureBuilder)); return builder; @@ -318,14 +238,9 @@ public static IHttpClientBuilder ConfigureHttpMessageHandlerBuilder(this IHttpCl /// /// public static IHttpClientBuilder AddTypedClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IHttpClientBuilder builder) + this IHttpClientBuilder builder!!) where TClient : class { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - return AddTypedClientCore(builder, validateSingleType: false); } @@ -383,15 +298,10 @@ private static TClient AddTransientHelper(IServiceProvider s, IHttpClie /// /// public static IHttpClientBuilder AddTypedClient( - this IHttpClientBuilder builder) + this IHttpClientBuilder builder!!) where TClient : class where TImplementation : class, TClient { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - return AddTypedClientCore(builder, validateSingleType: false); } @@ -439,19 +349,9 @@ 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 { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - return AddTypedClientCore(builder, factory, validateSingleType: false); } @@ -492,35 +392,15 @@ 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 { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(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 { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - ReserveClient(builder, typeof(TClient), builder.Name, validateSingleType); builder.Services.AddTransient(s => @@ -542,18 +422,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (shouldRedactHeaderValue == null) - { - throw new ArgumentNullException(nameof(shouldRedactHeaderValue)); - } - builder.Services.Configure(builder.Name, options => { options.ShouldRedactHeaderValue = shouldRedactHeaderValue; @@ -568,18 +438,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (redactedLoggedHeaderNames == null) - { - throw new ArgumentNullException(nameof(redactedLoggedHeaderNames)); - } - builder.Services.Configure(builder.Name, options => { var sensitiveHeaders = new HashSet(redactedLoggedHeaderNames, StringComparer.OrdinalIgnoreCase); @@ -614,13 +474,8 @@ 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) { - if (builder == null) - { - throw new ArgumentNullException(nameof(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 b0a34b788e4305..5a2ad822f7421a 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs @@ -20,13 +20,8 @@ public static class HttpClientFactoryServiceCollectionExtensions /// /// The . /// The . - public static IServiceCollection AddHttpClient(this IServiceCollection services) + public static IServiceCollection AddHttpClient(this IServiceCollection services!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - services.AddLogging(); services.AddOptions(); @@ -78,18 +73,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - AddHttpClient(services); return new DefaultHttpClientBuilder(services, name); @@ -112,23 +97,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -153,23 +123,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -200,14 +155,9 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, /// /// public static IHttpClientBuilder AddHttpClient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TClient>( - this IServiceCollection services) + this IServiceCollection services!!) where TClient : class { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -243,15 +193,10 @@ public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, /// /// public static IHttpClientBuilder AddHttpClient( - this IServiceCollection services) + this IServiceCollection services!!) where TClient : class where TImplementation : class, TClient { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -286,19 +231,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -337,20 +272,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -382,19 +307,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -428,19 +343,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -478,20 +383,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -529,20 +424,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); @@ -579,24 +464,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -632,24 +502,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -689,25 +544,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -747,25 +587,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (configureClient == null) - { - throw new ArgumentNullException(nameof(configureClient)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -799,20 +624,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); return AddHttpClient(services, name, factory); } @@ -845,25 +660,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - AddHttpClient(services); var builder = new DefaultHttpClientBuilder(services, name); @@ -896,20 +696,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - string name = TypeNameHelper.GetTypeDisplayName(typeof(TClient), fullName: false); return AddHttpClient(services, name, factory); } @@ -940,25 +730,10 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(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 876618f7a63d95..77c798f09740cf 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpClientFactoryExtensions.cs @@ -15,13 +15,8 @@ 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!!) { - if (factory == null) - { - throw new ArgumentNullException(nameof(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 862a33dfa523ef..9bbe559fe6a913 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerBuilder.cs @@ -76,21 +76,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!!) { // 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. - if (primaryHandler == null) - { - throw new ArgumentNullException(nameof(primaryHandler)); - } - - if (additionalHandlers == null) - { - throw new ArgumentNullException(nameof(additionalHandlers)); - } - IReadOnlyList additionalHandlersList = additionalHandlers as IReadOnlyList ?? additionalHandlers.ToArray(); HttpMessageHandler next = primaryHandler; diff --git a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs index d69c459d5b3b7b..823c1231669b96 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/HttpMessageHandlerFactoryExtensions.cs @@ -15,13 +15,8 @@ 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!!) { - if (factory == null) - { - throw new ArgumentNullException(nameof(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 cca20cbca1a1ed..c7c502be236e0c 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs @@ -25,13 +25,8 @@ public class LoggingHttpMessageHandler : DelegatingHandler /// /// The to log to. /// is . - public LoggingHttpMessageHandler(ILogger logger) + public LoggingHttpMessageHandler(ILogger logger!!) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - _logger = logger; } @@ -41,31 +36,16 @@ 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!!) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - _logger = logger; _options = options; } /// /// Loggs the request to and response from the sent . - protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected async override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - Func shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue; // Not using a scope here because we always expect this to be at the end of the pipeline, thus there's diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs index ebefa2047bb47d..b3a6f66004578f 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs @@ -14,29 +14,14 @@ 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!!) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } - - if (optionsMonitor == null) - { - throw new ArgumentNullException(nameof(optionsMonitor)); - } - _loggerFactory = loggerFactory; _optionsMonitor = optionsMonitor; } - public Action Configure(Action next) + public Action Configure(Action next!!) { - if (next == null) - { - throw new ArgumentNullException(nameof(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 92fab8b7d06f34..6b9536b92e01ed 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs @@ -25,13 +25,8 @@ public class LoggingScopeHttpMessageHandler : DelegatingHandler /// /// The to log to. /// is . - public LoggingScopeHttpMessageHandler(ILogger logger) + public LoggingScopeHttpMessageHandler(ILogger logger!!) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - _logger = logger; } @@ -41,31 +36,16 @@ 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!!) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - _logger = logger; _options = options; } /// /// Loggs the request to and response from the sent . - protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected async override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - var stopwatch = ValueStopwatch.StartNew(); Func shouldRedactHeaderValue = _options?.ShouldRedactHeaderValue ?? _shouldNotRedactHeaderValue; diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs index 24dfb06b014928..4d2b3e66c96a93 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs @@ -23,13 +23,8 @@ 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!!) { - if (format == null) - { - throw new ArgumentNullException(nameof(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 4ef6c371e2b918..64c53da7275d11 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerExtensions.cs @@ -383,13 +383,8 @@ 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) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter); } @@ -408,15 +403,10 @@ 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) { - if (logger == null) - { - throw new ArgumentNullException(nameof(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 96b02320918f74..6333a7e7b676f6 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs @@ -17,12 +17,8 @@ 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!!) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } return new Logger(factory); } /// @@ -31,18 +27,8 @@ 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!!) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(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 bea9a8bdeff700..05022936317194 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerT.cs @@ -19,13 +19,8 @@ public class Logger : ILogger /// Creates a new . /// /// The factory. - public Logger(ILoggerFactory factory) + public Logger(ILoggerFactory factory!!) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } - _logger = factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(typeof(T), includeGenericParameters: false, nestedTypeDelimiter: '.')); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs index cf6c22f67f37af..8d87d6b0fa2def 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParser.cs @@ -10,12 +10,8 @@ namespace Microsoft.Extensions.Logging.Console internal sealed class AnsiParser { private readonly Action _onParseWrite; - public AnsiParser(Action onParseWrite) + public AnsiParser(Action onParseWrite!!) { - if (onParseWrite == null) - { - throw new ArgumentNullException(nameof(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 716502fb33faa9..b4c20770f830c4 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleFormatter.cs @@ -12,9 +12,9 @@ namespace Microsoft.Extensions.Logging.Console /// public abstract class ConsoleFormatter { - protected ConsoleFormatter(string name) + protected ConsoleFormatter(string name!!) { - Name = name ?? throw new ArgumentNullException(nameof(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 906f703a8d679c..301ed0a9fbc5fc 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLogger.cs @@ -14,13 +14,8 @@ internal sealed class ConsoleLogger : ILogger private readonly string _name; private readonly ConsoleLoggerProcessor _queueProcessor; - internal ConsoleLogger(string name, ConsoleLoggerProcessor loggerProcessor) + internal ConsoleLogger(string name!!, ConsoleLoggerProcessor loggerProcessor) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - _name = name; _queueProcessor = loggerProcessor; } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs index 8a91327d95c32c..ef1e80a113627a 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerExtensions.cs @@ -44,13 +44,8 @@ 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!!) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } - builder.AddConsole(); builder.Services.Configure(configure); @@ -108,13 +103,9 @@ 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 { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } builder.AddFormatterWithName(name); builder.Services.Configure(configure); @@ -148,15 +139,10 @@ 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 { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } - builder.AddConsoleFormatter(); builder.Services.Configure(configure); return builder; diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs index 36501319caf438..c8eac36b02acb2 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs @@ -27,10 +27,10 @@ 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) { - _name = name ?? throw new ArgumentNullException(nameof(name)); - _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _name = name; + _settings = settings; _externalScopeProvider = externalScopeProvider; EventLog = settings.EventLog; diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs index 2c10135436a989..17c2c8b0466269 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLoggerFactoryExtensions.cs @@ -18,13 +18,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton()); return builder; @@ -36,18 +31,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (settings == null) - { - throw new ArgumentNullException(nameof(settings)); - } - builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(new EventLogLoggerProvider(settings))); return builder; @@ -59,13 +44,8 @@ public static ILoggingBuilder AddEventLog(this ILoggingBuilder builder, EventLog /// 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!!) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } - builder.AddEventLog(); builder.Services.Configure(configure); diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs index 5e6994495f4ddf..de15d2e5b0ea8f 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerFactoryExtensions.cs @@ -19,13 +19,8 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(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 3d6036f7c0b05a..e4e5e55872209c 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs @@ -20,12 +20,8 @@ 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!!) { - if (eventSource == null) - { - throw new ArgumentNullException(nameof(eventSource)); - } _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); } diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs index fb8320b4b179c6..d4288e3fd7bb80 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceFactoryExtensions.cs @@ -20,19 +20,9 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (switchName == null) - { - throw new ArgumentNullException(nameof(switchName)); - } - return builder.AddTraceSource(new SourceSwitch(switchName)); } @@ -44,25 +34,10 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (switchName == null) - { - throw new ArgumentNullException(nameof(switchName)); - } - - if (listener == null) - { - throw new ArgumentNullException(nameof(listener)); - } - return builder.AddTraceSource(new SourceSwitch(switchName), listener); } @@ -73,19 +48,9 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (sourceSwitch == null) - { - throw new ArgumentNullException(nameof(sourceSwitch)); - } - builder.Services.AddSingleton(_ => new TraceSourceLoggerProvider(sourceSwitch)); return builder; @@ -99,25 +64,10 @@ 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!!) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (sourceSwitch == null) - { - throw new ArgumentNullException(nameof(sourceSwitch)); - } - - if (listener == null) - { - throw new ArgumentNullException(nameof(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 c23fa4605d85b8..6983adab855cbe 100644 --- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/TraceSourceLoggerProvider.cs @@ -35,13 +35,8 @@ public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch) /// /// The to use. /// The to use. - public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch, TraceListener rootTraceListener) + public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch!!, TraceListener rootTraceListener) { - if (rootSourceSwitch == null) - { - throw new ArgumentNullException(nameof(rootSourceSwitch)); - } - _rootSourceSwitch = rootSourceSwitch; _rootTraceListener = rootTraceListener; } diff --git a/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs index 7e2e1a67f97cae..b04b31b87d4125 100644 --- a/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Logging/src/LoggingServiceCollectionExtensions.cs @@ -29,13 +29,8 @@ 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) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - services.AddOptions(); services.TryAdd(ServiceDescriptor.Singleton()); diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs index 2a414c7bce237e..225d1abb43a3d0 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs @@ -21,19 +21,16 @@ public class ConfigurationChangeTokenSource : IOptionsChangeTokenSourc /// /// The configuration instance. public ConfigurationChangeTokenSource(IConfiguration config) : this(Options.DefaultName, config) - { } + { + } /// /// Constructor taking the instance to watch. /// /// The name of the options instance being watched. /// The configuration instance. - public ConfigurationChangeTokenSource(string name, IConfiguration config) + public ConfigurationChangeTokenSource(string name, IConfiguration config!!) { - if (config == null) - { - throw new ArgumentNullException(nameof(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 b9b3d00ee1fba2..c0bd89c168ea24 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigureFromConfigurationOptions.cs @@ -23,13 +23,9 @@ 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)) { - if (config == null) - { - throw new ArgumentNullException(nameof(config)); - } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs index df5b7e4cb92a3f..78c791abea2a94 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/NamedConfigureFromConfigurationOptions.cs @@ -32,13 +32,9 @@ public NamedConfigureFromConfigurationOptions(string name, IConfiguration config /// 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)) { - if (config == null) - { - throw new ArgumentNullException(nameof(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 128f0eda38aa4a..d020d8a5df9453 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsBuilderConfigurationExtensions.cs @@ -35,13 +35,8 @@ 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 { - if (optionsBuilder == null) - { - throw new ArgumentNullException(nameof(optionsBuilder)); - } - optionsBuilder.Services.Configure(optionsBuilder.Name, config, configureBinder); return optionsBuilder; } @@ -61,13 +56,13 @@ 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 { - _ = optionsBuilder ?? throw new ArgumentNullException(nameof(optionsBuilder)); - _ = configSectionPath ?? throw new ArgumentNullException(nameof(configSectionPath)); + _ = optionsBuilder; + _ = configSectionPath; optionsBuilder.Configure((opts, config) => BindFromOptions(opts, config, configSectionPath, configureBinder)); optionsBuilder.Services.AddSingleton, ConfigurationChangeTokenSource>(); diff --git a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs index 3606ae73f9a274..8851b87e5460c2 100644 --- a/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/OptionsConfigurationServiceCollectionExtensions.cs @@ -59,19 +59,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (config == null) - { - throw new ArgumentNullException(nameof(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/src/ConfigureNamedOptions.cs b/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs index bd1d1c3bd80484..cf4bc8c9230fd2 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ConfigureNamedOptions.cs @@ -37,13 +37,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -100,13 +95,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -172,13 +162,8 @@ public ConfigureNamedOptions(string name, TDep1 dependency, TDep2 dependency2, A /// /// 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -253,13 +238,8 @@ public ConfigureNamedOptions(string name, TDep1 dependency, TDep2 dependency2, T /// /// 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -343,13 +323,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -442,13 +417,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(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 2e9a98aea8c2e4..fa9c3b86b3d5b6 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/ConfigureOptions.cs @@ -29,13 +29,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - Action?.Invoke(options); } } diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs index 56a41617f9d8bf..a1baf74bb97b95 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs @@ -29,13 +29,8 @@ 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) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - Services = services; Name = name ?? Options.DefaultName; } @@ -46,13 +41,8 @@ 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!!) { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddSingleton>(new ConfigureNamedOptions(Name, configureOptions)); return this; } @@ -64,14 +54,9 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>(sp => new ConfigureNamedOptions(Name, sp.GetRequiredService(), configureOptions)); return this; @@ -85,15 +70,10 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>(sp => new ConfigureNamedOptions(Name, sp.GetRequiredService(), sp.GetRequiredService(), configureOptions)); return this; @@ -108,16 +88,11 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>( sp => new ConfigureNamedOptions( Name, @@ -138,17 +113,12 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>( sp => new ConfigureNamedOptions( Name, @@ -171,18 +141,13 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>( sp => new ConfigureNamedOptions( Name, @@ -200,13 +165,8 @@ public virtual OptionsBuilder Configure. /// /// The action used to configure the options. - public virtual OptionsBuilder PostConfigure(Action configureOptions) + public virtual OptionsBuilder PostConfigure(Action configureOptions!!) { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddSingleton>(new PostConfigureOptions(Name, configureOptions)); return this; } @@ -218,14 +178,9 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>(sp => new PostConfigureOptions(Name, sp.GetRequiredService(), configureOptions)); return this; @@ -239,15 +194,10 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>(sp => new PostConfigureOptions(Name, sp.GetRequiredService(), sp.GetRequiredService(), configureOptions)); return this; @@ -262,16 +212,11 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>( sp => new PostConfigureOptions( Name, @@ -292,17 +237,12 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>( sp => new PostConfigureOptions( Name, @@ -325,18 +265,13 @@ 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 { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - Services.AddTransient>( sp => new PostConfigureOptions( Name, @@ -363,13 +298,8 @@ 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) { - if (validation == null) - { - throw new ArgumentNullException(nameof(validation)); - } - Services.AddSingleton>(new ValidateOptions(Name, validation, failureMessage)); return this; } @@ -390,13 +320,8 @@ 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) { - if (validation == null) - { - throw new ArgumentNullException(nameof(validation)); - } - Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), validation, failureMessage)); return this; @@ -420,13 +345,8 @@ 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) { - if (validation == null) - { - throw new ArgumentNullException(nameof(validation)); - } - Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), @@ -456,13 +376,8 @@ 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) { - if (validation == null) - { - throw new ArgumentNullException(nameof(validation)); - } - Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), @@ -495,13 +410,8 @@ 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) { - if (validation == null) - { - throw new ArgumentNullException(nameof(validation)); - } - Services.AddTransient>(sp => new ValidateOptions(Name, sp.GetRequiredService(), @@ -537,13 +447,8 @@ 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) { - if (validation == null) - { - throw new ArgumentNullException(nameof(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 7bc3914072a001..f431291de7468e 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsCache.cs @@ -28,14 +28,9 @@ 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!!) { - if (createOptions == null) - { - throw new ArgumentNullException(nameof(createOptions)); - } - - name = name ?? Options.DefaultName; + name ??= Options.DefaultName; Lazy value; #if NETSTANDARD2_1 @@ -74,13 +69,8 @@ internal bool TryGetValue(string name, out TOptions options) /// 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - return _cache.TryAdd(name ?? Options.DefaultName, new Lazy( #if !NETSTANDARD2_1 () => diff --git a/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs b/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs index a84cbe19e1fa6f..eff6706bbb3a8c 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs @@ -19,13 +19,8 @@ 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!!) { - if (services == null) - { - throw new ArgumentNullException(nameof(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<>))); @@ -54,19 +49,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - services.AddOptions(); services.AddSingleton>(new ConfigureNamedOptions(name, configureOptions)); return services; @@ -102,19 +87,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } - services.AddOptions(); services.AddSingleton>(new PostConfigureOptions(name, configureOptions)); return services; @@ -250,14 +225,9 @@ 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 { - if (services == null) - { - throw new ArgumentNullException(nameof(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 3c3e238240301a..b20e18583ec6b4 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/OptionsValidationException.cs @@ -17,11 +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) { Failures = failureMessages ?? new List(); - OptionsType = optionsType ?? throw new ArgumentNullException(nameof(optionsType)); - OptionsName = optionsName ?? throw new ArgumentNullException(nameof(optionsName)); + 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 4ec0bbca3a906f..5049ef1330043b 100644 --- a/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Options/src/PostConfigureOptions.cs @@ -37,13 +37,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to initialize all named options. if (Name == null || name == Name) { @@ -94,13 +89,8 @@ 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -166,13 +156,8 @@ public PostConfigureOptions(string name, TDep1 dependency, TDep2 dependency2, Ac /// /// 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -247,13 +232,8 @@ public PostConfigureOptions(string name, TDep1 dependency, TDep2 dependency2, TD /// /// 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -337,13 +317,8 @@ public PostConfigureOptions(string name, TDep1 dependency1, 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { @@ -436,13 +411,8 @@ public PostConfigureOptions(string name, TDep1 dependency1, 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!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - // Null name is used to configure all named options. if (Name == null || name == Name) { diff --git a/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs b/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs index d0ddc8b8143f3b..45a35ff3c0fffc 100644 --- a/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs +++ b/src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs @@ -18,17 +18,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(changeTokenProducer)); - } - if (changeTokenConsumer == null) - { - throw new ArgumentNullException(nameof(changeTokenConsumer)); - } - return new ChangeTokenRegistration(changeTokenProducer, callback => callback(), changeTokenConsumer); } @@ -39,17 +30,8 @@ public static IDisposable OnChange(Func changeTokenProducer, Acti /// 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 == null) - { - throw new ArgumentNullException(nameof(changeTokenProducer)); - } - if (changeTokenConsumer == null) - { - throw new ArgumentNullException(nameof(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 7df86773f7d728..070c7ad148f697 100644 --- a/src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs +++ b/src/libraries/Microsoft.Extensions.Primitives/src/CompositeChangeToken.cs @@ -27,9 +27,9 @@ public class CompositeChangeToken : IChangeToken /// Creates a new instance of . /// /// The list of to compose. - public CompositeChangeToken(IReadOnlyList changeTokens) + public CompositeChangeToken(IReadOnlyList changeTokens!!) { - ChangeTokens = changeTokens ?? throw new ArgumentNullException(nameof(changeTokens)); + ChangeTokens = changeTokens; for (int i = 0; i < ChangeTokens.Count; i++) { if (ChangeTokens[i].ActiveChangeCallbacks) 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 ea3b3f88eb7481..094b6bf351d602 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,27 +8,18 @@ namespace Microsoft.Win32 { public static class RegistryAclExtensions { - public static RegistrySecurity GetAccessControl(this RegistryKey key) + public static RegistrySecurity GetAccessControl(this RegistryKey key!!) { - if (key == 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 == 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 == 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 49eeecff31ab0c..094a87b9c5be82 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/Registry.cs @@ -33,13 +33,8 @@ 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) { - if (keyName == null) - { - throw new ArgumentNullException(nameof(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 c82feafee9f0c6..49d2c2f3a7d973 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -323,12 +323,8 @@ 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) { - if (machineName == null) - { - throw new ArgumentNullException(nameof(machineName)); - } ValidateKeyView(view); return OpenRemoteBaseKeyCore(hKey, machineName, view); @@ -405,10 +401,7 @@ public RegistrySecurity GetAccessControl(AccessControlSections includeSections) public void SetAccessControl(RegistrySecurity registrySecurity) { EnsureWriteable(); - if (registrySecurity == null) - { - throw new ArgumentNullException(nameof(registrySecurity)); - } + ArgumentNullException.ThrowIfNull(registrySecurity); registrySecurity.Persist(Handle, Name); } @@ -447,9 +440,8 @@ 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) { - if (handle == null) throw new ArgumentNullException(nameof(handle)); ValidateKeyView(view); return new RegistryKey(handle, writable: true, view: view); @@ -557,13 +549,8 @@ 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) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (name != null && name.Length > MaxValueLength) { throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); @@ -721,13 +708,8 @@ private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) } } - private static void ValidateKeyName(string name) + private static void ValidateKeyName(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(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 e62a31e4d28c6d..1dc2afa7ab821d 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -545,12 +545,8 @@ 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 == 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 ef64456aa2646f..cf872800a7bd96 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -516,13 +516,8 @@ private void GenerateNamespace(CodeNamespace e) GenerateNamespaceEnd(e); } - private void GenerateStatement(CodeStatement e) + private void GenerateStatement(CodeStatement e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); @@ -2680,13 +2675,8 @@ public void ValidateIdentifier(string value) } } - public string CreateValidIdentifier(string name) + public string CreateValidIdentifier(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (CSharpHelpers.IsPrefixTwoUnderscore(name)) { name = "_" + name; @@ -2700,13 +2690,8 @@ public string CreateValidIdentifier(string name) return name; } - public string CreateEscapedIdentifier(string name) + public string CreateEscapedIdentifier(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - return CSharpHelpers.CreateEscapedIdentifier(name); } @@ -2887,13 +2872,8 @@ private void OutputStartingBrace() } } - CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit e) + CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options!!, CodeCompileUnit e) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromDom(options, e); @@ -2904,13 +2884,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, } } - CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) + CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options!!, string fileName) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromFile(options, fileName); @@ -2921,13 +2896,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options } } - CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) + CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options!!, string source) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromSource(options, source); @@ -2938,13 +2908,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio } } - CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) + CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options!!, string[] sources) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromSourceBatch(options, sources); @@ -2955,17 +2920,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters } } - CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) + CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options!!, string[] fileNames!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileNames == null) - { - throw new ArgumentNullException(nameof(fileNames)); - } - try { // Try opening the files to make sure they exists. This will throw an exception @@ -2983,13 +2939,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op } } - CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) + CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options!!, CodeCompileUnit[] ea) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromDomBatch(options, ea); @@ -3000,28 +2951,14 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters opt } } - private CompilerResults FromDom(CompilerParameters options, CodeCompileUnit e) + private CompilerResults FromDom(CompilerParameters options!!, CodeCompileUnit e) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - return FromDomBatch(options, new CodeCompileUnit[1] { e }); } - private CompilerResults FromFile(CompilerParameters options, string fileName) + private CompilerResults FromFile(CompilerParameters options!!, string fileName!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileName == 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(); @@ -3029,27 +2966,13 @@ private CompilerResults FromFile(CompilerParameters options, string fileName) return FromFileBatch(options, new string[1] { fileName }); } - private CompilerResults FromSource(CompilerParameters options, string source) + private CompilerResults FromSource(CompilerParameters options!!, string source) { - if (options == 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 == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (ea == null) - { - throw new ArgumentNullException(nameof(ea)); - } - string[] filenames = new string[ea.Length]; for (int i = 0; i < ea.Length; i++) @@ -3086,17 +3009,8 @@ private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompile } } - private CompilerResults FromSourceBatch(CompilerParameters options, string[] sources) + private CompilerResults FromSourceBatch(CompilerParameters options!!, string[] sources!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (sources == 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 04677068e1bac3..4fabb5ce695162 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeProvider.cs @@ -20,13 +20,8 @@ public CSharpCodeProvider() _generator = new CSharpCodeGenerator(); } - public CSharpCodeProvider(IDictionary providerOptions) + public CSharpCodeProvider(IDictionary providerOptions!!) { - if (providerOptions == 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 23371016fa05b6..b1837dc2c7b68c 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpModifierAttributeConverter.cs @@ -34,13 +34,8 @@ 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 == 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 0417b41b668d18..7f67555914f70a 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeProvider.cs @@ -20,13 +20,8 @@ public VBCodeProvider() _generator = new VBCodeGenerator(); } - public VBCodeProvider(IDictionary providerOptions) + public VBCodeProvider(IDictionary providerOptions!!) { - if (providerOptions == 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 affa1d3c66c391..c4742449c99234 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBModiferAttributeConverter.cs @@ -34,13 +34,8 @@ 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 == 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 5db624817188ac..c8f40a7d1f2732 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeArgumentCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 942d26368d254e..32fe51fbef9377 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeAttributeDeclarationCollection.cs @@ -29,26 +29,16 @@ 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 == 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 == 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 a825620e8ec8e9..0217b111b0ff84 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClauseCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 8a8dc513818405..7ad005f6659a5d 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCommentStatementCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 797d978473e9ce..522148078a17e0 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeDirectiveCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 7b9c731cf69240..62a8a77c1ca742 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeExpressionCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 ccd0bffe19d2d5..dc8163b3c97b60 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 bb63f182dd5df0..c86444e3cb0333 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeNamespaceImportCollection.cs @@ -36,13 +36,8 @@ public void Add(CodeNamespaceImport value) } } - public void AddRange(CodeNamespaceImport[] value) + public void AddRange(CodeNamespaceImport[] value!!) { - if (value == 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 d9ff397330c3cc..933fea75089d06 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpressionCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 5999b37c7ee5ee..c0ecd53ab960b8 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatementCollection.cs @@ -29,26 +29,16 @@ 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 == 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 == 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 242506fb267a3b..19101e49e608ed 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclarationCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 caa36a5130bf2f..32683b4379c224 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMemberCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 8b00ec1c267f5e..67e6c51160be39 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameterCollection.cs @@ -29,26 +29,16 @@ 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 == 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 == 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 9e24a113117c8a..25ee9eefcb1b25 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs @@ -8,13 +8,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromDom(options, e); @@ -25,13 +20,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromDom(CompilerParameters options, } } - CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options, string fileName) + CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options!!, string fileName) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromFile(options, fileName); @@ -42,13 +32,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFile(CompilerParameters options } } - CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options, string source) + CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters options!!, string source) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromSource(options, source); @@ -59,13 +44,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSource(CompilerParameters optio } } - CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) + CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters options!!, string[] sources) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromSourceBatch(options, sources); @@ -76,17 +56,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch(CompilerParameters } } - CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) + CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options!!, string[] fileNames!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileNames == 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 @@ -103,13 +74,8 @@ CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters op } } - CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) + CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options!!, CodeCompileUnit[] ea) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - try { return FromDomBatch(options, ea); @@ -124,26 +90,13 @@ 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 == 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 == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileName == 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(); @@ -151,27 +104,13 @@ protected virtual CompilerResults FromFile(CompilerParameters options, string fi 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 == 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 == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (ea == null) - { - throw new ArgumentNullException(nameof(ea)); - } - var filenames = new string[ea.Length]; for (int i = 0; i < ea.Length; i++) @@ -208,17 +147,8 @@ private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompile } } - protected virtual CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) + protected virtual CompilerResults FromFileBatch(CompilerParameters options!!, string[] fileNames!!) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (fileNames == null) - { - throw new ArgumentNullException(nameof(fileNames)); - } - throw new PlatformNotSupportedException(); } @@ -240,17 +170,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(options)); - } - if (sources == 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 72284ad5ad6b70..6e984975c8c690 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeDomProvider.cs @@ -86,25 +86,15 @@ public static CompilerInfo GetCompilerInfo(string language) return compilerInfo; } - private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language) + private static CompilerInfo GetCompilerInfoForLanguageNoThrow(string language!!) { - if (language == 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 == 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 60c0117280cd15..b7b3b24af68288 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeGenerator.cs @@ -232,13 +232,8 @@ protected void GenerateNamespaces(CodeCompileUnit e) } } - protected void GenerateTypes(CodeNamespace e) + protected void GenerateTypes(CodeNamespace e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - foreach (CodeTypeDeclaration c in e.Types) { if (_options.BlankLinesBetweenMembers) @@ -398,12 +393,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(member)); - } if (_output != null) { throw new InvalidOperationException(SR.CodeGenReentrance); @@ -710,13 +701,8 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) } } - protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) + protected virtual void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - GenerateDirectives(e.StartDirectives); if (e.LinePragma != null) @@ -800,13 +786,8 @@ protected virtual void GenerateCompileUnit(CodeCompileUnit e) GenerateCompileUnitEnd(e); } - protected virtual void GenerateNamespace(CodeNamespace e) + protected virtual void GenerateNamespace(CodeNamespace e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - GenerateCommentStatements(e.Comments); GenerateNamespaceStart(e); @@ -817,13 +798,8 @@ protected virtual void GenerateNamespace(CodeNamespace e) GenerateNamespaceEnd(e); } - protected void GenerateNamespaceImports(CodeNamespace e) + protected void GenerateNamespaceImports(CodeNamespace e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - foreach (CodeNamespaceImport imp in e.Imports) { if (imp.LinePragma != null) @@ -874,13 +850,8 @@ private void GenerateProperties(CodeTypeDeclaration e) } } - protected void GenerateStatement(CodeStatement e) + protected void GenerateStatement(CodeStatement e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - if (e.StartDirectives.Count > 0) { GenerateDirectives(e.StartDirectives); @@ -971,25 +942,16 @@ protected void GenerateStatement(CodeStatement e) } } - protected void GenerateStatements(CodeStatementCollection stmts) + protected void GenerateStatements(CodeStatementCollection stmts!!) { - if (stmts == 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 == null) - { - throw new ArgumentNullException(nameof(attributes)); - } if (attributes.Count == 0) { return; @@ -1031,13 +993,8 @@ protected virtual void OutputAttributeDeclarations(CodeAttributeDeclarationColle GenerateAttributeDeclarationsEnd(attributes); } - protected virtual void OutputAttributeArgument(CodeAttributeArgument arg) + protected virtual void OutputAttributeArgument(CodeAttributeArgument arg!!) { - if (arg == null) - { - throw new ArgumentNullException(nameof(arg)); - } - if (!string.IsNullOrEmpty(arg.Name)) { OutputIdentifier(arg.Name); @@ -1287,13 +1244,8 @@ protected virtual void OutputOperator(CodeBinaryOperatorType op) } } - protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters) + protected virtual void OutputParameters(CodeParameterDeclarationExpressionCollection parameters!!) { - if (parameters == null) - { - throw new ArgumentNullException(nameof(parameters)); - } - bool first = true; bool multiline = parameters.Count > ParameterMultilineThreshold; if (multiline) @@ -1325,13 +1277,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(e)); - } - bool indentedExpression = false; Output.Write('('); @@ -1381,13 +1328,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(e)); - } - if (e.CustomAttributes.Count > 0) { OutputAttributeDeclarations(e.CustomAttributes); @@ -1398,24 +1340,14 @@ protected virtual void GenerateParameterDeclarationExpression(CodeParameterDecla OutputTypeNamePair(e.Type, e.Name); } - protected virtual void GenerateDirectionExpression(CodeDirectionExpression e) + protected virtual void GenerateDirectionExpression(CodeDirectionExpression e!!) { - if (e == 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 == null) - { - throw new ArgumentNullException(nameof(e)); - } - if (e.Value == null) { Output.Write(NullToken); @@ -1489,23 +1421,13 @@ 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 == null) - { - throw new ArgumentNullException(nameof(e)); - } - OutputType(e.Type); } - protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e) + protected virtual void GenerateTypeOfExpression(CodeTypeOfExpression e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - Output.Write("typeof("); OutputType(e.Type); Output.Write(')'); @@ -1514,12 +1436,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(e)); - } if (e.Comment == null) { throw new ArgumentException(SR.Format(SR.Argument_NullComment, nameof(e)), nameof(e)); @@ -1527,13 +1445,8 @@ protected virtual void GenerateCommentStatement(CodeCommentStatement e) GenerateComment(e.Comment); } - protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e) + protected virtual void GenerateCommentStatements(CodeCommentStatementCollection e!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } - foreach (CodeCommentStatement comment in e) { GenerateCommentStatement(comment); @@ -1550,13 +1463,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(e)); - } - Output.WriteLine(e.Value); } @@ -1574,26 +1482,16 @@ 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 == 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 == 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 cd806bc7f5ceea..f2c970d1afd046 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -433,13 +433,8 @@ private void ValidateComment(CodeComment e) { } - private void ValidateStatement(CodeStatement e) + private void ValidateStatement(CodeStatement e!!) { - if (e == 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 5ececb97f7ade1..a85476820e1740 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerErrorCollection.cs @@ -27,26 +27,16 @@ 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 == 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 == 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 84c19410797fde..ac3b334a04de95 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerInfo.cs @@ -63,13 +63,8 @@ public CodeDomProvider CreateProvider() return (CodeDomProvider)Activator.CreateInstance(CodeDomProviderType); } - public CodeDomProvider CreateProvider(IDictionary providerOptions) + public CodeDomProvider CreateProvider(IDictionary providerOptions!!) { - if (providerOptions == 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/Resources/Strings.resx b/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx index f09a978890740a..d6ddb52224e693 100644 --- a/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx +++ b/src/libraries/System.Collections.Concurrent/src/Resources/Strings.resx @@ -114,12 +114,6 @@ The collections argument is a zero-length array. - - The collection argument is null. - - - The array argument is null. - The index argument must be greater than or equal zero. 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 1685d4ee52b00b..92aaa08fba65f5 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,7 +173,7 @@ 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) { if (boundedCapacity < 1) { @@ -181,10 +181,7 @@ public BlockingCollection(IProducerConsumerCollection collection, int bounded nameof(boundedCapacity), boundedCapacity, SR.BlockingCollection_ctor_BoundedCapacityRange); } - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + int count = collection.Count; if (count > boundedCapacity) { @@ -199,12 +196,8 @@ public BlockingCollection(IProducerConsumerCollection collection, int bounded /// The collection to use as the underlying data store. /// The argument is /// null. - public BlockingCollection(IProducerConsumerCollection collection) + public BlockingCollection(IProducerConsumerCollection collection!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } Initialize(collection, NON_BOUNDED, collection.Count); } @@ -1698,12 +1691,8 @@ 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) { - if (collections == null) - { - throw new ArgumentNullException(nameof(collections)); - } if (collections.Length < 1) { throw new ArgumentException( @@ -1787,13 +1776,8 @@ 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!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(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 9930d13a3a0bbd..25f7d4451584ca 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,13 +53,8 @@ public ConcurrentBag() /// cref="ConcurrentBag{T}"/>. /// is a null reference /// (Nothing in Visual Basic). - public ConcurrentBag(IEnumerable collection) + public ConcurrentBag(IEnumerable collection!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection), SR.ConcurrentBag_Ctor_ArgumentNullException); - } - _locals = new ThreadLocal(); WorkStealingQueue queue = GetCurrentThreadWorkStealingQueue(forceCreate: true)!; @@ -277,12 +272,8 @@ private bool TryStealFromTo(WorkStealingQueue? startInclusive, WorkStealingQueue /// -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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array), SR.ConcurrentBag_CopyTo_ArgumentNullException); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.Collection_CopyTo_ArgumentOutOfRangeException); @@ -375,10 +366,7 @@ void ICollection.CopyTo(Array array, int index) // Otherwise, fall back to first storing the contents to an array, // and then relying on its CopyTo to copy to the target Array. - if (array == null) - { - throw new ArgumentNullException(nameof(array), SR.ConcurrentBag_CopyTo_ArgumentNullException); - } + ArgumentNullException.ThrowIfNull(array); ToArray().CopyTo(array, index); } 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 f237d7024d6d99..c170a7e46da588 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,14 +139,9 @@ 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) { - if (collection is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(collection)); - } - InitializeFromCollection(collection); } @@ -165,14 +160,9 @@ 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) { - if (collection is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(collection)); - } - InitializeFromCollection(collection); } @@ -676,13 +666,8 @@ 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) { - if (array is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(array)); - } - if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ConcurrentDictionary_IndexIsNegative); @@ -1804,13 +1789,8 @@ 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) { - if (array is null) - { - ThrowHelper.ThrowArgumentNullException(nameof(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 9a4af6b378c4f5..7416c2c9c17c0c 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,12 +76,8 @@ public ConcurrentStack() /// cref="ConcurrentStack{T}"/>. /// The argument is /// null. - public ConcurrentStack(IEnumerable collection) + public ConcurrentStack(IEnumerable collection!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } InitializeFromCollection(collection); } @@ -224,14 +220,8 @@ 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) { - // Validate arguments. - if (array == null) - { - throw new ArgumentNullException(nameof(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 @@ -259,13 +249,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 @@ -310,12 +295,8 @@ 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!!) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } PushRange(items, 0, items.Length); } @@ -398,12 +379,8 @@ 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) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ConcurrentStack_PushPopRange_CountOutOfRange); @@ -511,13 +488,8 @@ 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!!) { - if (items == null) - { - throw new ArgumentNullException(nameof(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 3d494454c0f2be..b06acd06eb6e75 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,12 +85,8 @@ 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) { - if (list == null) - { - throw new ArgumentNullException(nameof(list)); - } if (loadBalance) { return (new DynamicPartitionerForIList(list)); @@ -113,15 +109,11 @@ 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) { // This implementation uses 'ldelem' instructions for element retrieval, rather than using a // method call. - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } if (loadBalance) { return (new DynamicPartitionerForArray(array)); @@ -166,13 +158,8 @@ 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) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if ((partitionerOptions & (~EnumerablePartitionerOptions.NoBuffering)) != 0) throw new ArgumentOutOfRangeException(nameof(partitionerOptions)); diff --git a/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx b/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx index 2f022b658b9ea7..57a2b3f07016ff 100644 --- a/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx +++ b/src/libraries/System.Collections.NonGeneric/src/Resources/Strings.resx @@ -78,9 +78,6 @@ Dictionary cannot be null. - - Key cannot be null. - Index was out of range. Must be non-negative and less than the size of the collection. 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 a104d6518122ec..88c10aca600797 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveComparer.cs @@ -24,12 +24,8 @@ public CaseInsensitiveComparer() _compareInfo = CultureInfo.CurrentCulture.CompareInfo; } - public CaseInsensitiveComparer(CultureInfo culture) + public CaseInsensitiveComparer(CultureInfo culture!!) { - if (culture == null) - { - throw new ArgumentNullException(nameof(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 b121b442540a12..2d8cdeefa9c003 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs @@ -20,12 +20,8 @@ public CaseInsensitiveHashCodeProvider() _compareInfo = CultureInfo.CurrentCulture.CompareInfo; } - public CaseInsensitiveHashCodeProvider(CultureInfo culture) + public CaseInsensitiveHashCodeProvider(CultureInfo culture!!) { - if (culture == null) - { - throw new ArgumentNullException(nameof(culture)); - } _compareInfo = culture.CompareInfo; } @@ -34,13 +30,8 @@ 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!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(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 086be37456c27e..37a5bd2768f299 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CollectionBase.cs @@ -225,9 +225,8 @@ protected virtual void OnRemove(int index, object? value) { } - protected virtual void OnValidate(object value) + protected virtual void OnValidate(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(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 748729d3615ab7..617fc139e04007 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Queue.cs @@ -66,11 +66,8 @@ 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 == null ? 32 : col.Count)) + public Queue(ICollection col!!) : this(col.Count) { - if (col == null) - throw new ArgumentNullException(nameof(col)); - IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Enqueue(en.Current); @@ -129,10 +126,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) @@ -210,11 +205,8 @@ 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!!) { - if (queue == null) - throw new ArgumentNullException(nameof(queue)); - return new SynchronizedQueue(queue); } @@ -490,11 +482,8 @@ internal sealed class QueueDebugView { private readonly Queue _queue; - public QueueDebugView(Queue queue) + public QueueDebugView(Queue queue!!) { - if (queue == null) - throw new ArgumentNullException(nameof(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 db5465c70f7e64..aee2560164c0c9 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/SortedList.cs @@ -151,12 +151,9 @@ 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 != null ? d.Count : 0)) + public SortedList(IDictionary d!!, IComparer? comparer) + : this(comparer, d.Count) { - if (d == null) - throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary); - d.Keys.CopyTo(keys, 0); d.Values.CopyTo(values, 0); @@ -173,10 +170,8 @@ 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) { - if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_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)); @@ -334,10 +329,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -465,7 +458,7 @@ public virtual object? this[object key] } set { - if (key == null) throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + ArgumentNullException.ThrowIfNull(key); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) { @@ -484,10 +477,8 @@ 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!!) { - if (key == null) - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } @@ -558,10 +549,8 @@ 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!!) { - if (list == null) - throw new ArgumentNullException(nameof(list)); return new SyncSortedList(list); } @@ -737,11 +726,8 @@ public override IList GetValueList() } } - public override int IndexOfKey(object key) + public override int IndexOfKey(object key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - lock (_root) { return _list.IndexOfKey(key); @@ -981,8 +967,7 @@ public IEnumerator GetEnumerator() public int IndexOf(object? key) { - if (key == null) - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); + ArgumentNullException.ThrowIfNull(key); int i = Array.BinarySearch(sortedList.keys, 0, sortedList.Count, key, sortedList.comparer); @@ -1104,13 +1089,8 @@ internal sealed class SortedListDebugView { private readonly SortedList _sortedList; - public SortedListDebugView(SortedList sortedList) + public SortedListDebugView(SortedList sortedList!!) { - if (sortedList == null) - { - throw new ArgumentNullException(nameof(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 9d4f87df218bc5..1ecbd9907950da 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/Stack.cs @@ -53,11 +53,8 @@ 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 == null ? 32 : col.Count) + public Stack(ICollection col!!) : this(col.Count) { - if (col == null) - throw new ArgumentNullException(nameof(col)); - IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Push(en.Current); @@ -115,10 +112,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) @@ -191,11 +186,8 @@ public virtual void Push(object? obj) // Returns a synchronized Stack. // - public static Stack Synchronized(Stack stack) + public static Stack Synchronized(Stack stack!!) { - if (stack == null) - throw new ArgumentNullException(nameof(stack)); - return new SyncStack(stack); } @@ -388,11 +380,8 @@ internal sealed class StackDebugView { private readonly Stack _stack; - public StackDebugView(Stack stack) + public StackDebugView(Stack stack!!) { - if (stack == null) - throw new ArgumentNullException(nameof(stack)); - _stack = stack; } diff --git a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs index eaf4375b4abc4d..be3f840c898280 100644 --- a/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs +++ b/src/libraries/System.Collections.Specialized/src/System/Collections/Specialized/HybridDictionary.cs @@ -81,9 +81,9 @@ public object? this[object key] // (2) There is writer which is doing ChangeOver. However in that case // we should see the change to hashtable as well. // So it should work just fine. - else if (key == null) + else { - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); } return null; } @@ -287,9 +287,9 @@ public bool Contains(object key) { return cachedList.Contains(key); } - else if (key == null) + else { - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); } return false; } @@ -342,9 +342,9 @@ public void Remove(object key) { list.Remove(key); } - else if (key == null) + else { - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); } } } 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 daa68a87bdb6c0..a16848cc7a3ff0 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,14 +30,10 @@ public ListDictionary(IComparer? comparer) this.comparer = comparer; } - public object? this[object key] + public object? this[object key!!] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } DictionaryNode? node = head; if (comparer == null) { @@ -67,10 +63,6 @@ public object? this[object key] } set { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } version++; DictionaryNode? last = null; DictionaryNode? node; @@ -155,12 +147,8 @@ public ICollection Values } } - public void Add(object key, object? value) + public void Add(object key!!, object? value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } version++; DictionaryNode? last = null; @@ -195,12 +183,8 @@ public void Clear() version++; } - public bool Contains(object key) + public bool Contains(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } for (DictionaryNode? node = head; node != null; node = node.next) { object oldKey = node.key; @@ -212,10 +196,8 @@ public bool Contains(object key) return false; } - public void CopyTo(Array array, int index) + public void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); @@ -239,12 +221,8 @@ IEnumerator IEnumerable.GetEnumerator() return new NodeEnumerator(this); } - public void Remove(object key) + public void Remove(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } version++; DictionaryNode? last = null; DictionaryNode? node; @@ -373,10 +351,8 @@ public NodeKeyValueCollection(ListDictionary list, bool isKeys) _isKeys = isKeys; } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(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 5810ddd3551eb5..b9ad8cd08c1825 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,13 +363,8 @@ public virtual int Count } } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (array.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(array)); @@ -434,13 +429,9 @@ 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!!) { int n = _entriesArray.Count; - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } object?[] allValues = (object?[])Array.CreateInstance(type, n); for (int i = 0; i < n; i++) @@ -601,13 +592,8 @@ public int Count } } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 0b4d4f0a75400c..10999012096be1 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,14 +76,9 @@ 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 != null ? col.Comparer : null)) + public NameValueCollection(int capacity, NameValueCollection col!!) + : base(capacity, col.Comparer) { - if (col == null) - { - throw new ArgumentNullException(nameof(col)); - } - this.Comparer = col.Comparer; Add(col); } @@ -157,13 +152,8 @@ protected void InvalidateCachedArrays() /// /// Copies the entries in the specified to the current . /// - public void Add(NameValueCollection c) + public void Add(NameValueCollection c!!) { - if (c == null) - { - throw new ArgumentNullException(nameof(c)); - } - InvalidateCachedArrays(); int n = c.Count; @@ -198,13 +188,8 @@ public virtual void Clear() BaseClear(); } - public void CopyTo(Array dest, int index) + public void CopyTo(Array dest!!, int index) { - if (dest == null) - { - throw new ArgumentNullException(nameof(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 0aacb55866cb11..0be13d70d9f07f 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,12 +260,8 @@ public OrderedDictionary AsReadOnly() /// /// Returns true if the key exists in the table, false otherwise. /// - public bool Contains(object key) + public bool Contains(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } if (_objectsTable == null) { return false; @@ -357,10 +353,7 @@ public void Remove(object key) { throw new NotSupportedException(SR.OrderedDictionary_ReadOnly); } - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullException.ThrowIfNull(key); int index = IndexOfKey(key); if (index < 0) @@ -391,13 +384,8 @@ IEnumerator IEnumerable.GetEnumerator() #endregion #region ISerializable implementation - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer)); info.AddValue(ReadOnlyName, _readOnly); info.AddValue(InitCapacityName, _initialCapacity); @@ -566,10 +554,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(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 0ffc7ac0822ce7..d92f78a5515ef6 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,12 +69,8 @@ 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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 436514bf1773eb..103a1ffd6926be 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,24 +62,14 @@ 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 { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return (string?)contents[key.ToLowerInvariant()]; } set { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - contents[key.ToLowerInvariant()] = value; } } @@ -121,13 +111,8 @@ 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) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - contents.Add(key.ToLowerInvariant(), value); } @@ -142,13 +127,8 @@ 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!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return contents.ContainsKey(key.ToLowerInvariant()); } @@ -180,13 +160,8 @@ 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!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(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 288a6c94c944c7..b299ec73be9f02 100644 --- a/src/libraries/System.Collections.Specialized/tests/OrderedDictionary/CaseInsensitiveEqualityComparer.cs +++ b/src/libraries/System.Collections.Specialized/tests/OrderedDictionary/CaseInsensitiveEqualityComparer.cs @@ -25,13 +25,8 @@ internal sealed class CaseInsensitiveEqualityComparer : IEqualityComparer return x.Equals(y); } - public int GetHashCode(object obj) + public int GetHashCode(object obj!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(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 925f175f7fcf8f..2ae1185bafb498 100644 --- a/src/libraries/System.Collections/src/System/Collections/BitArray.cs +++ b/src/libraries/System.Collections/src/System/Collections/BitArray.cs @@ -74,13 +74,8 @@ public BitArray(int length, bool defaultValue) ** ** Exceptions: ArgumentException if bytes == null. =========================================================================*/ - public BitArray(byte[] bytes) + public BitArray(byte[] bytes!!) { - if (bytes == null) - { - throw new ArgumentNullException(nameof(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. @@ -126,13 +121,8 @@ 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!!) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } - m_array = new int[GetInt32ArrayLengthFromBitLength(values.Length)]; m_length = values.Length; @@ -197,13 +187,8 @@ public unsafe BitArray(bool[] values) ** ** Exceptions: ArgumentException if values == null. =========================================================================*/ - public BitArray(int[] values) + public BitArray(int[] values!!) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } - // this value is chosen to prevent overflow when computing m_length if (values.Length > int.MaxValue / BitsPerInt32) { @@ -222,13 +207,8 @@ public BitArray(int[] values) ** ** Exceptions: ArgumentException if bits == null. =========================================================================*/ - public BitArray(BitArray bits) + public BitArray(BitArray bits!!) { - if (bits == null) - { - throw new ArgumentNullException(nameof(bits)); - } - int arrayLength = GetInt32ArrayLengthFromBitLength(bits.m_length); m_array = new int[arrayLength]; @@ -321,11 +301,8 @@ 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!!) { - if (value == null) - throw new ArgumentNullException(nameof(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 @@ -388,11 +365,8 @@ 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!!) { - if (value == null) - throw new ArgumentNullException(nameof(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 @@ -455,11 +429,8 @@ 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!!) { - if (value == null) - throw new ArgumentNullException(nameof(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 @@ -737,11 +708,8 @@ public int Length } } - public unsafe void CopyTo(Array array, int index) + public unsafe void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(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 4f5c545603dbbe..ce35e1b9b8c961 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs @@ -13,24 +13,14 @@ 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) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(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) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } - if (!dictionary.ContainsKey(key)) { dictionary.Add(key, value); @@ -40,13 +30,8 @@ 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) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(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 00431d4eeb47b0..acb0f425c76a35 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs @@ -28,13 +28,8 @@ public LinkedList() { } - public LinkedList(IEnumerable collection) + public LinkedList(IEnumerable collection!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - foreach (T item in collection) { AddLast(item); @@ -191,13 +186,8 @@ public bool Contains(T value) return Find(value) != null; } - public void CopyTo(T[] array, int index) + public void CopyTo(T[] array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -331,15 +321,11 @@ public void RemoveLast() InternalRemoveNode(head.prev!); } - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) { // 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. - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } info.AddValue(VersionName, version); info.AddValue(CountName, count); // this is the length of the bucket array. @@ -427,26 +413,16 @@ internal void InternalRemoveNode(LinkedListNode node) version++; } - internal void ValidateNewNode(LinkedListNode node) + internal void ValidateNewNode(LinkedListNode node!!) { - if (node == null) - { - throw new ArgumentNullException(nameof(node)); - } - if (node.list != null) { throw new InvalidOperationException(SR.LinkedListNodeIsAttached); } } - internal void ValidateNode(LinkedListNode node) + internal void ValidateNode(LinkedListNode node!!) { - if (node == null) - { - throw new ArgumentNullException(nameof(node)); - } - if (node.list != this) { throw new InvalidOperationException(SR.ExternalLinkedListNode); @@ -460,13 +436,8 @@ bool ICollection.IsSynchronized object ICollection.SyncRoot => this; - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 a9fbb3f8375cae..b2937c17c3901d 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs @@ -157,13 +157,8 @@ 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) { - if (items is null) - { - throw new ArgumentNullException(nameof(items)); - } - _nodes = EnumerableHelpers.ToArray(items, out _size); _comparer = InitializeComparer(comparer); @@ -351,13 +346,8 @@ 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!!) { - if (items is null) - { - throw new ArgumentNullException(nameof(items)); - } - int count = 0; var collection = items as ICollection<(TElement Element, TPriority Priority)>; if (collection is not null && (count = collection.Count) > _nodes.Length - _size) @@ -417,13 +407,8 @@ 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) { - if (elements is null) - { - throw new ArgumentNullException(nameof(elements)); - } - int count; if (elements is ICollection<(TElement Element, TPriority Priority)> collection && (count = collection.Count) > _nodes.Length - _size) @@ -815,13 +800,8 @@ 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) { - if (array is null) - { - throw new ArgumentNullException(nameof(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 0a99e8c2b534f6..b0799caa63ab5b 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueueDebugView.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueueDebugView.cs @@ -10,9 +10,9 @@ internal sealed class PriorityQueueDebugView private readonly PriorityQueue _queue; private readonly bool _sort; - public PriorityQueueDebugView(PriorityQueue queue) + public PriorityQueueDebugView(PriorityQueue queue!!) { - _queue = queue ?? throw new ArgumentNullException(nameof(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 c28fa0123728c8..007eb4c74b257e 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedDictionary.cs @@ -28,13 +28,8 @@ public SortedDictionary(IDictionary dictionary) : this(dictionary, { } - public SortedDictionary(IDictionary dictionary, IComparer? comparer) + public SortedDictionary(IDictionary dictionary!!, IComparer? comparer) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } - var keyValuePairComparer = new KeyValuePairComparer(comparer); if (dictionary is SortedDictionary sortedDictionary && @@ -209,12 +204,8 @@ IEnumerable IReadOnlyDictionary.Values } } - public void Add(TKey key, TValue value) + public void Add(TKey key!!, TValue value) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } _set.Add(new KeyValuePair(key, value)); } @@ -223,13 +214,8 @@ public void Clear() _set.Clear(); } - public bool ContainsKey(TKey key) + public bool ContainsKey(TKey key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return _set.Contains(new KeyValuePair(key, default(TValue)!)); } @@ -279,23 +265,13 @@ IEnumerator> IEnumerable>. return new Enumerator(this, Enumerator.KeyValuePair); } - public bool Remove(TKey key) + public bool Remove(TKey key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(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) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - TreeSet>.Node? node = _set.FindNode(new KeyValuePair(key, default(TValue)!)); if (node == null) { @@ -375,16 +351,13 @@ ICollection IDictionary.Values } } - void IDictionary.Add(object key, object? value) + void IDictionary.Add(object key!!, object? value) { - if (key == null) + if (default(TValue) != null) { - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(value); } - if (value == null && default(TValue) != null) - throw new ArgumentNullException(nameof(value)); - try { TKey tempKey = (TKey)key; @@ -413,13 +386,8 @@ bool IDictionary.Contains(object key) return false; } - private static bool IsCompatibleKey(object key) + private static bool IsCompatibleKey(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return (key is TKey); } @@ -568,12 +536,8 @@ public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCol { private readonly SortedDictionary _dictionary; - public KeyCollection(SortedDictionary dictionary) + public KeyCollection(SortedDictionary dictionary!!) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } _dictionary = dictionary; } @@ -592,13 +556,8 @@ IEnumerator IEnumerable.GetEnumerator() return new Enumerator(_dictionary); } - public void CopyTo(TKey[] array, int index) + public void CopyTo(TKey[] array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -612,13 +571,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -750,12 +704,8 @@ public sealed class ValueCollection : ICollection, ICollection, IReadOnl { private readonly SortedDictionary _dictionary; - public ValueCollection(SortedDictionary dictionary) + public ValueCollection(SortedDictionary dictionary!!) { - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } _dictionary = dictionary; } @@ -774,13 +724,8 @@ IEnumerator IEnumerable.GetEnumerator() return new Enumerator(_dictionary); } - public void CopyTo(TValue[] array, int index) + public void CopyTo(TValue[] array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -794,13 +739,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 1a96e7c79d18e3..5037964ae0342c 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -147,12 +147,9 @@ 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 != null ? dictionary.Count : 0), comparer) + public SortedList(IDictionary dictionary!!, IComparer? comparer) + : this(dictionary.Count, comparer) { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - int count = dictionary.Count; if (count != 0) { @@ -180,9 +177,8 @@ public SortedList(IDictionary dictionary, IComparer? compare // 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) { - if (key == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); @@ -265,11 +261,8 @@ public IComparer Comparer } } - void IDictionary.Add(object key, object? value) + void IDictionary.Add(object key!!, object? value) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - if (value == null && default(TValue) != null) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); @@ -442,13 +435,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); @@ -466,13 +454,8 @@ void ICollection>.CopyTo(KeyValuePair[] } } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -649,10 +632,8 @@ 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!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); int ret = Array.BinarySearch(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } @@ -754,13 +735,8 @@ public void TrimExcess() } } - private static bool IsCompatibleKey(object key) + private static bool IsCompatibleKey(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return (key is TKey); } @@ -1109,11 +1085,8 @@ IEnumerator IEnumerable.GetEnumerator() return new SortedListKeyEnumerator(_dict); } - public int IndexOf(TKey key) + public int IndexOf(TKey key!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 a0de9bd1dc8f04..a076ecf4d632fb 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -80,14 +80,9 @@ 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) { - if (collection == null) - { - throw new ArgumentNullException(nameof(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; @@ -510,13 +505,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); @@ -546,13 +536,8 @@ public void CopyTo(T[] array, int index, int count) }); } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); @@ -858,13 +843,8 @@ private bool HasEqualComparer(SortedSet other) #region ISet members - public void UnionWith(IEnumerable other) + public void UnionWith(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - SortedSet? asSorted = other as SortedSet; TreeSubSet? treeSubset = this as TreeSubSet; @@ -1001,13 +981,8 @@ public void UnionWith(IEnumerable other) return root; } - public virtual void IntersectWith(IEnumerable other) + public virtual void IntersectWith(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (Count == 0) return; @@ -1086,13 +1061,8 @@ internal virtual void IntersectWithEnumerable(IEnumerable other) } } - public void ExceptWith(IEnumerable other) + public void ExceptWith(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (count == 0) return; @@ -1127,13 +1097,8 @@ public void ExceptWith(IEnumerable other) } } - public void SymmetricExceptWith(IEnumerable other) + public void SymmetricExceptWith(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (Count == 0) { UnionWith(other); @@ -1197,13 +1162,8 @@ private void SymmetricExceptWithSameComparer(T[] other, int count) } } - public bool IsSubsetOf(IEnumerable other) + public bool IsSubsetOf(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (Count == 0) { return true; @@ -1235,13 +1195,8 @@ private bool IsSubsetOfSortedSetWithSameComparer(SortedSet asSorted) return true; } - public bool IsProperSubsetOf(IEnumerable other) + public bool IsProperSubsetOf(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (other is ICollection c) { if (Count == 0) @@ -1262,13 +1217,8 @@ public bool IsProperSubsetOf(IEnumerable other) return result.UniqueCount == Count && result.UnfoundCount > 0; } - public bool IsSupersetOf(IEnumerable other) + public bool IsSupersetOf(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (other is ICollection c && c.Count == 0) return true; @@ -1292,13 +1242,8 @@ public bool IsSupersetOf(IEnumerable other) return ContainsAllElements(other); } - public bool IsProperSupersetOf(IEnumerable other) + public bool IsProperSupersetOf(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (Count == 0) return false; @@ -1327,13 +1272,8 @@ public bool IsProperSupersetOf(IEnumerable other) return result.UniqueCount < Count && result.UnfoundCount == 0; } - public bool SetEquals(IEnumerable other) + public bool SetEquals(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - SortedSet? asSorted = other as SortedSet; if (asSorted != null && HasEqualComparer(asSorted)) { @@ -1358,13 +1298,8 @@ public bool SetEquals(IEnumerable other) return result.UniqueCount == Count && result.UnfoundCount == 0; } - public bool Overlaps(IEnumerable other) + public bool Overlaps(IEnumerable other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (Count == 0) return false; @@ -1470,12 +1405,8 @@ private unsafe ElementCount CheckUniqueAndUnfoundElements(IEnumerable other, return result; } - public int RemoveWhere(Predicate match) + public int RemoveWhere(Predicate match!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } List matches = new List(this.Count); BreadthFirstTreeWalk(n => @@ -1577,13 +1508,8 @@ 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) { - if (info == null) - { - throw new ArgumentNullException(nameof(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 76e9af5b0ca380..1855c01248540b 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs @@ -48,10 +48,8 @@ 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!!) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); _array = EnumerableHelpers.ToArray(collection, out _size); } @@ -94,13 +92,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); @@ -120,13 +113,8 @@ public void CopyTo(T[] array, int arrayIndex) } } - void ICollection.CopyTo(Array array, int arrayIndex) + void ICollection.CopyTo(Array array!!, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 92709a55ca6419..bbb5ed33c93b78 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/StackDebugView.cs @@ -9,13 +9,8 @@ internal sealed class StackDebugView { private readonly Stack _stack; - public StackDebugView(Stack stack) + public StackDebugView(Stack stack!!) { - if (stack == null) - { - throw new ArgumentNullException(nameof(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 fbfe36a6c888b8..52d67ed2ce5cf7 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,14 +33,9 @@ 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) { - if (associatedMetadataType == null) - { - throw new ArgumentNullException(nameof(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 4e3b82cf4fa6ad..5f1fe3536c6338 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,9 +12,9 @@ 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) { - OtherProperty = otherProperty ?? throw new ArgumentNullException(nameof(otherProperty)); + OtherProperty = otherProperty; } public string OtherProperty { get; } 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 41fad8c6539971..4314563f23aba3 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,13 +406,8 @@ 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!!) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } - var result = IsValid(value, validationContext); // If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage @@ -476,13 +471,8 @@ 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!!) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(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 650a114e5af50d..a086b9cfd1e57d 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,12 +135,8 @@ 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!!) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(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 836bf43ac9f77a..58163389f9a4f0 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,13 +84,8 @@ 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) { - if (instance == null) - { - throw new ArgumentNullException(nameof(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 fa26fd83bd1816..004d66ca0fde8a 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,13 +65,8 @@ public ValidationResult(string? errorMessage, IEnumerable? memberNames) /// /// The validation result. /// The is null. - protected ValidationResult(ValidationResult validationResult) + protected ValidationResult(ValidationResult validationResult!!) { - if (validationResult == null) - { - throw new ArgumentNullException(nameof(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 3e409406079949..53ce73aa522a13 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,14 +130,9 @@ 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) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - if (validationContext != null && instance != validationContext.ObjectInstance) { throw new ArgumentException(SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); @@ -186,10 +181,8 @@ public static bool TryValidateObject(object instance, ValidationContext validati /// /// 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; @@ -276,17 +269,9 @@ 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) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } if (instance != validationContext.ObjectInstance) { throw new ArgumentException(SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); @@ -316,12 +301,9 @@ public static void ValidateObject(object instance, ValidationContext validationC /// 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) { @@ -409,15 +391,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) { Debug.Assert(instance != null); - if (validationContext == null) - { - throw new ArgumentNullException(nameof(validationContext)); - } - // Step 1: Validate the object properties' validation attributes var errors = new List(); errors.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties, @@ -563,13 +540,8 @@ 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) { - if (validationContext == null) - { - throw new ArgumentNullException(nameof(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 2d9b046570ecbc..854321cddaaa8d 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 @@ -98,90 +98,64 @@ public PartBuilder ExportInterfaces() return ExportInterfaces(t => true, null); } - public PartBuilder ExportInterfaces(Predicate interfaceFilter, + public PartBuilder ExportInterfaces(Predicate interfaceFilter!!, Action exportConfiguration) { - if (interfaceFilter == 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 == null) - throw new ArgumentNullException(nameof(propertyFilter)); - return ExportProperties(propertyFilter, null); } - public PartBuilder ExportProperties(Predicate propertyFilter, + public PartBuilder ExportProperties(Predicate propertyFilter!!, Action exportConfiguration) { - if (propertyFilter == 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 == null) - throw new ArgumentNullException(nameof(propertyFilter)); - return ExportProperties(propertyFilter, null); } - public PartBuilder ExportProperties(Predicate propertyFilter, + public PartBuilder ExportProperties(Predicate propertyFilter!!, Action exportConfiguration) { - if (propertyFilter == 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 == null) - throw new ArgumentNullException(nameof(propertyFilter)); - return ImportProperties(propertyFilter, null); } - public PartBuilder ImportProperties(Predicate propertyFilter, + public PartBuilder ImportProperties(Predicate propertyFilter!!, Action importConfiguration) { - if (propertyFilter == 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 == null) - throw new ArgumentNullException(nameof(propertyFilter)); - return ImportProperties(propertyFilter, null); } - public PartBuilder ImportProperties(Predicate propertyFilter, + public PartBuilder ImportProperties(Predicate propertyFilter!!, Action importConfiguration) { - if (propertyFilter == 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 a85c31ef87f605..657c5853f72bb6 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,11 +39,8 @@ public void ConfigureExport(PropertyInfo propertyInfo, ExportBuilder exportBuild _configureExport?.Invoke(exportBuilder); } - private static PropertyInfo SelectProperties(Expression> propertyFilter) + private static PropertyInfo SelectProperties(Expression> propertyFilter!!) { - if (propertyFilter == null) - throw new ArgumentNullException(nameof(propertyFilter)); - Expression expr = Reduce(propertyFilter).Body; if (expr.NodeType == ExpressionType.MemberAccess) { @@ -92,11 +89,8 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportBuild } } - private void ParseSelectConstructor(Expression> constructorFilter) + private void ParseSelectConstructor(Expression> constructorFilter!!) { - if (constructorFilter == null) - throw new ArgumentNullException(nameof(constructorFilter)); - Expression expr = Reduce(constructorFilter).Body; if (expr.NodeType != ExpressionType.New) { @@ -150,11 +144,8 @@ internal PartBuilder(Predicate selectType) : base(selectType) { } - public PartBuilder SelectConstructor(Expression> constructorFilter) + public PartBuilder SelectConstructor(Expression> constructorFilter!!) { - if (constructorFilter == null) - throw new ArgumentNullException(nameof(constructorFilter)); - var adapter = new ConstructorExpressionAdapter(constructorFilter); SelectConstructor(adapter.SelectConstructor, adapter.ConfigureConstructorImports); @@ -168,12 +159,9 @@ public PartBuilder ExportProperty(Expression> propertyFilter) } public PartBuilder ExportProperty( - Expression> propertyFilter, + Expression> propertyFilter!!, Action exportConfiguration) { - if (propertyFilter == null) - throw new ArgumentNullException(nameof(propertyFilter)); - var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -185,12 +173,9 @@ public PartBuilder ExportProperty(Expression> prop return ExportProperty(propertyFilter, null); } - public PartBuilder ExportProperty(Expression> propertyFilter, + public PartBuilder ExportProperty(Expression> propertyFilter!!, Action exportConfiguration) { - if (propertyFilter == null) - throw new ArgumentNullException(nameof(propertyFilter)); - var adapter = new PropertyExpressionAdapter(propertyFilter, null, exportConfiguration); ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); @@ -202,12 +187,9 @@ public PartBuilder ImportProperty(Expression> propertyFilter) return ImportProperty(propertyFilter, null); } - public PartBuilder ImportProperty(Expression> propertyFilter, + public PartBuilder ImportProperty(Expression> propertyFilter!!, Action importConfiguration) { - if (propertyFilter == null) - throw new ArgumentNullException(nameof(propertyFilter)); - var adapter = new PropertyExpressionAdapter(propertyFilter, importConfiguration, null); ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); @@ -219,12 +201,9 @@ public PartBuilder ImportProperty(Expression> prop return ImportProperty(propertyFilter, null); } - public PartBuilder ImportProperty(Expression> propertyFilter, + public PartBuilder ImportProperty(Expression> propertyFilter!!, Action importConfiguration) { - if (propertyFilter == 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 9ed87a0ff35e23..fa82204739a881 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,11 +38,8 @@ public PartBuilder ForTypesDerivedFrom() return partBuilder; } - public PartBuilder ForTypesDerivedFrom(Type type) + public PartBuilder ForTypesDerivedFrom(Type type!!) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - var partBuilder = new PartBuilder((t) => type != t && type.IsAssignableFrom(t)); _conventions.Add(partBuilder); @@ -57,33 +54,24 @@ public PartBuilder ForType() return partBuilder; } - public PartBuilder ForType(Type type) + public PartBuilder ForType(Type type!!) { - if (type == 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 == 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 == 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 55249fc22f7b9b..9ef2fd2f361428 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,18 +9,8 @@ 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!!) { - if (itemType == null) - { - throw new ArgumentNullException(nameof(itemType)); - } - - if (collectionObject == null) - { - throw new ArgumentNullException(nameof(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 c41333296127f1..1c0fcb03d57a89 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,13 +56,8 @@ public static bool IsEnumerableOfT(Type type) return null; } - public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable source) + public static ReadOnlyCollection ToReadOnlyCollection(this IEnumerable source!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return new ReadOnlyCollection(source.AsArray()); } @@ -168,13 +163,8 @@ public static void ForEach(this IEnumerable source, Action action) } } - public static EnumerableCardinality GetCardinality(this IEnumerable source) + public static EnumerableCardinality GetCardinality(this IEnumerable source!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - // Cast to ICollection instead of ICollection for performance reasons. if (source is ICollection collection) { @@ -202,13 +192,8 @@ public static EnumerableCardinality GetCardinality(this IEnumerable source } } - public static Stack Copy(this Stack stack) + public static Stack Copy(this Stack stack!!) { - if (stack == null) - { - throw new ArgumentNullException(nameof(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 036811b5ae93cb..10df9f5c97ba5d 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/GenerationServices.cs @@ -162,25 +162,10 @@ 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!!) { Debug.Assert(ilGenerator != null); - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - ilGenerator.Emit(OpCodes.Ldloc, dictionary); ilGenerator.LoadValue(key); ilGenerator.LoadValue(value); @@ -192,25 +177,10 @@ 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!!) { Debug.Assert(ilGenerator != null); - if (dictionary == null) - { - throw new ArgumentNullException(nameof(dictionary)); - } - - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - ilGenerator.Emit(OpCodes.Ldloc, dictionary); ilGenerator.LoadValue(key); ilGenerator.Emit(OpCodes.Ldloc, value); @@ -221,34 +191,19 @@ 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!!) { Debug.Assert(ilGenerator != null); - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - if (dataStore == null) - { - throw new ArgumentNullException(nameof(dataStore)); - } - ilGenerator.Emit(OpCodes.Ldloc, exception); ilGenerator.Emit(OpCodes.Callvirt, ExceptionGetData); ilGenerator.Emit(OpCodes.Stloc, dataStore); } - private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable) + private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable!!) { Debug.Assert(ilGenerator != null); - if (enumerable == null) - { - throw new ArgumentNullException(nameof(enumerable)); - } - // We load enumerable as an array - this is the most compact and efficient way of representing it Type elementType; if (ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), GenerationServices.s_iEnumerableTypeofT, out Type? closedType)) 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 0e8ecae85fa8ed..e20f13ae89d870 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/LazyServices.cs @@ -2,20 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Globalization; 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 { - if (lazy == null) - { - throw new ArgumentNullException(nameof(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 d6ec08259a05b8..e3f8b040bf9419 100644 --- a/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/Microsoft/Internal/ReflectionServices.cs @@ -57,23 +57,13 @@ 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) { - if (declaringType == null) - { - throw new ArgumentNullException(nameof(name)); - } - return declaringType.GetDisplayName() + "." + name; } - public static string GetDisplayName(this MemberInfo member) + public static string GetDisplayName(this MemberInfo member!!) { - if (member == null) - { - throw new ArgumentNullException(nameof(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 b37ca10ac9ed55..ff61848f49ae83 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,24 +18,9 @@ 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) { - if (partCreationInfo == null) - { - throw new ArgumentNullException(nameof(partCreationInfo)); - } - - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - - if (exportAttribute == null) - { - throw new ArgumentNullException(nameof(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 f2f498827c0b51..9e5d2207492f4a 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,43 +24,23 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (attributedPart == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (attributedPart == null) - { - throw new ArgumentNullException(nameof(attributedPart)); - } - - if (reflectionContext == null) - { - throw new ArgumentNullException(nameof(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) @@ -73,19 +53,8 @@ public static ReflectionComposablePart CreatePart(object attributedPart, Reflect return CreatePart(definition, attributedPart); } - public static ReflectionComposablePart CreatePart(ComposablePartDefinition partDefinition, object attributedPart) + public static ReflectionComposablePart CreatePart(ComposablePartDefinition partDefinition!!, object attributedPart!!) { - if (partDefinition == null) - { - throw new ArgumentNullException(nameof(partDefinition)); - } - - if (attributedPart == null) - { - throw new ArgumentNullException(nameof(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 e59154c185a5ef..34d611c7e21218 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,13 +24,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - _type = type; _ignoreConstructorImports = ignoreConstructorImports; _partCreationPolicy = partCreationPolicy; @@ -187,13 +182,8 @@ private CreationPolicy CreationPolicy } } - private static ConstructorInfo? SelectPartConstructor(Type type) + private static ConstructorInfo? SelectPartConstructor(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 c7e74e85cc5e20..56974a4043d41b 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,31 +53,16 @@ public static Expression> CreateConstraint(string c return constraint; } - private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter) + private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter!!) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (requiredMetadata == null) - { - throw new ArgumentNullException(nameof(requiredMetadata)); - } - - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - Expression? body = null; foreach (KeyValuePair requiredMetadataItem in requiredMetadata) { @@ -91,18 +76,13 @@ 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!!) { if (policy == CreationPolicy.Any) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - // !definition.Metadata.ContainsKey(CompositionConstants.PartCreationPolicyMetadataName) || // CreationPolicy.Any.Equals(definition.Metadata[CompositionConstants.PartCreationPolicyMetadataName]) || // policy.Equals(definition.Metadata[CompositionConstants.PartCreationPolicyMetadataName]); @@ -114,18 +94,8 @@ 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!!) { - if (requiredTypeIdentity == null) - { - throw new ArgumentNullException(requiredTypeIdentity); - } - - if (parameter == null) - { - throw new ArgumentException(nameof(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 08c4bfb717e068..fe502db6365a18 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,13 +41,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 80a171cc1b776d..67259b1149a227 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,18 +32,8 @@ public static CompositionError ComposeTookTooManyIterations(int maximumNumberOfC maximumNumberOfCompositionIterations); } - public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception, ImportDefinition definition) + public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception!!, ImportDefinition definition!!) { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - return CompositionError.Create( CompositionErrorId.ImportEngine_ImportCardinalityMismatch, exception.Message, @@ -51,18 +41,8 @@ public static CompositionError CreateImportCardinalityMismatch(ImportCardinality (Exception?)null); } - public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException) + public static CompositionError CreatePartCannotActivate(ComposablePart part!!, Exception innerException!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } - - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } - ICompositionElement element = part.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCannotActivate, @@ -72,23 +52,8 @@ public static CompositionError CreatePartCannotActivate(ComposablePart part, Exc element.DisplayName); } - public static CompositionError CreatePartCannotSetImport(ComposablePart part, ImportDefinition definition, Exception innerException) + public static CompositionError CreatePartCannotSetImport(ComposablePart part!!, ImportDefinition definition!!, Exception innerException!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } - - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } - ICompositionElement element = definition.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCannotSetImport, @@ -99,23 +64,8 @@ public static CompositionError CreatePartCannotSetImport(ComposablePart part, Im part.ToElement().DisplayName); } - public static CompositionError CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException) + public static CompositionError CreateCannotGetExportedValue(ComposablePart part!!, ExportDefinition definition!!, Exception innerException!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } - - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } - ICompositionElement element = definition.ToElement(); return CompositionError.Create( CompositionErrorId.ImportEngine_PartCannotGetExportedValue, @@ -126,13 +76,8 @@ public static CompositionError CreateCannotGetExportedValue(ComposablePart part, part.ToElement().DisplayName); } - public static CompositionError CreatePartCycle(ComposablePart part) + public static CompositionError CreatePartCycle(ComposablePart part!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(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 dea39fb6e6f43f..0279e161ff7f42 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,35 +16,20 @@ 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!!) { - if (parameterName == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return new ObjectDisposedException(instance.GetType().ToString()); } - public static NotImplementedException CreateNotOverriddenByDerived(string memberName) + public static NotImplementedException CreateNotOverriddenByDerived(string memberName!!) { - if (memberName == null) - { - throw new ArgumentNullException(nameof(memberName)); - } - if (memberName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(memberName)), nameof(memberName)); @@ -55,13 +40,8 @@ public static NotImplementedException CreateNotOverriddenByDerived(string member return new NotImplementedException(message); } - public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName) + public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName!!) { - if (parameterName == null) - { - throw new ArgumentNullException(nameof(parameterName)); - } - if (parameterName.Length == 0) { throw new ArgumentException(SR.ArgumentException_EmptyString); @@ -73,13 +53,8 @@ public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(st return new ArgumentException(message, parameterName); } - public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName) + public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName!!) { - if (parameterName == null) - { - throw new ArgumentNullException(nameof(parameterName)); - } - if (parameterName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(parameterName)), nameof(parameterName)); @@ -90,34 +65,14 @@ 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!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } - - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - - if (innerException == null) - { - throw new ArgumentNullException(nameof(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) { - if (parameterName == null) - { - throw new ArgumentNullException(nameof(parameterName)); - } - if (parameterName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(parameterName)), nameof(parameterName)); @@ -131,13 +86,8 @@ 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!!) { - if (typeName == null) - { - throw new ArgumentNullException(nameof(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 a5547d23532306..37fe04226567d6 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,13 +7,8 @@ public class ExportFactory { private readonly Func> _exportLifetimeContextCreator; - public ExportFactory(Func> exportLifetimeContextCreator) + public ExportFactory(Func> exportLifetimeContextCreator!!) { - if (exportLifetimeContextCreator == null) - { - throw new ArgumentNullException(nameof(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 1f9c8004676f77..bfbcb4b96347e8 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,14 +11,9 @@ 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) { - if (disposable == null) - { - throw new ArgumentNullException(nameof(disposable)); - } - _disposable = disposable; } @@ -32,14 +27,9 @@ 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) { - if (disposable == null) - { - throw new ArgumentNullException(nameof(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 af5e86056da17b..fff07d2d958ae6 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,26 +23,16 @@ 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!!) { - if (metadataViewType == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (metadataViewType == null) - { - throw new ArgumentNullException(nameof(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 e0d99e469252ac..e07e233f5798d3 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,13 +6,8 @@ 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 { - if (defaultResultAndKey == null) - { - throw new ArgumentNullException(nameof(defaultResultAndKey)); - } - return GetValueAllowNull(atomicComposition, defaultResultAndKey, defaultResultAndKey); } @@ -27,13 +22,8 @@ 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!!) { - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - if (atomicComposition == null) { action(); @@ -44,13 +34,8 @@ 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!!) { - if (action == null) - { - throw new ArgumentNullException(nameof(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 c10f2e48d045a2..d79e0c71f586cb 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,17 +13,8 @@ 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!!) { - if (catalogExportProvider == null) - { - throw new ArgumentNullException(nameof(catalogExportProvider)); - } - if (scopeDefinition == null) - { - throw new ArgumentNullException(nameof(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 b981f8cd8a7e1d..81f7d21230c959 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,12 +22,8 @@ private sealed class InnerCatalogExportProvider : ExportProvider { private readonly CatalogExportProvider _outerExportProvider; - public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider) + public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider!!) { - if (outerExportProvider == null) - { - throw new ArgumentNullException(nameof(outerExportProvider)); - } _outerExportProvider = outerExportProvider; } @@ -566,13 +562,8 @@ 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) { - if (catalogPart == null) - { - throw new ArgumentNullException(nameof(catalogPart)); - } - if (_isDisposed) return; @@ -620,18 +611,8 @@ private void DisposePart(object? exportedValue, CatalogPart catalogPart, AtomicC } } - private void PreventPartCollection(object exportedValue, ComposablePart part) + private void PreventPartCollection(object exportedValue!!, ComposablePart part!!) { - if (exportedValue == null) - { - throw new ArgumentNullException(nameof(exportedValue)); - } - - if (part == null) - { - throw new ArgumentNullException(nameof(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 8e17e23540e164..3e771180e8be5d 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,13 +318,8 @@ public void Compose(CompositionBatch batch) result.ThrowOnErrors(); } - private List GetUpdatedPartsList(ref CompositionBatch batch) + private List GetUpdatedPartsList(ref CompositionBatch batch!!) { - if (batch == null) - { - throw new ArgumentNullException(nameof(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 @@ -361,13 +356,8 @@ private List GetUpdatedPartsList(ref CompositionBatch batch) return parts; } - private void Recompose(CompositionBatch batch, AtomicComposition atomicComposition) + private void Recompose(CompositionBatch batch!!, AtomicComposition atomicComposition) { - if (batch == null) - { - throw new ArgumentNullException(nameof(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 e2f8250d304796..700c77b942b8e1 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,13 +15,8 @@ private sealed class SingleExportComposablePart : ComposablePart { private readonly Export _export; - public SingleExportComposablePart(Export export) + public SingleExportComposablePart(Export export!!) { - if (export == null) - { - throw new ArgumentNullException(nameof(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 afdc59810599e2..9a75cd080afe73 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,12 +11,8 @@ private sealed class CompositionServiceShim : ICompositionService { private readonly CompositionContainer _innerContainer; - public CompositionServiceShim(CompositionContainer innerContainer) + public CompositionServiceShim(CompositionContainer innerContainer!!) { - if (innerContainer == null) - { - throw new ArgumentNullException(nameof(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 ee9b9d80eb4565..ef625dcbdd9fba 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,13 +184,8 @@ public override IEnumerable> G return _catalog.GetExports(definition); } - internal IEnumerable> GetExportsFromPublicSurface(ImportDefinition definition) + internal IEnumerable> GetExportsFromPublicSurface(ImportDefinition definition!!) { - if (definition == null) - { - throw new ArgumentNullException(nameof(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 624adf905b8f5b..2f3fe14433b246 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,13 +17,8 @@ public class CompositionService : ICompositionService, IDisposable private readonly CompositionContainer? _compositionContainer; private readonly INotifyComposablePartCatalogChanged? _notifyCatalog; - internal CompositionService(ComposablePartCatalog composablePartCatalog) + internal CompositionService(ComposablePartCatalog composablePartCatalog!!) { - if (composablePartCatalog == null) - { - throw new ArgumentNullException(nameof(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 3df3463c0b2111..0447aef747c02b 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,13 +23,8 @@ internal static class CompositionServices CompositionConstants.PartCreationPolicyMetadataName }; - internal static Type GetDefaultTypeFromMember(this MemberInfo member) + internal static Type GetDefaultTypeFromMember(this MemberInfo member!!) { - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - switch (member.MemberType) { case MemberTypes.Property: @@ -61,13 +56,8 @@ 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) { - if (specifiedContractType == null) - { - throw new ArgumentNullException(nameof(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 @@ -406,13 +396,8 @@ public void Add(object? item, Type? itemType) _innerList.Add(item); } - private void InferArrayType(Type itemType) + private void InferArrayType(Type itemType!!) { - if (itemType == null) - { - throw new ArgumentNullException(nameof(itemType)); - } - if (_arrayType == null) { // this is the first typed element we've been given, it sets the type of the array @@ -627,13 +612,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 8ddbd6c5368902..4b571813a5888a 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,23 +794,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (metadataViewType == null) - { - throw new ArgumentNullException(nameof(metadataViewType)); - } - - if (contractName == null) - { - throw new ArgumentNullException(nameof(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 d17e1210684af3..78be23bdd6704c 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,13 +205,8 @@ 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) { - if (definition == null) - { - throw new ArgumentNullException(nameof(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 4c991d6542de12..7877e487f8a0f6 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,17 +17,8 @@ internal sealed class DependenciesTraversal : IComposablePartCatalogTraversal private readonly Func _importFilter; private Dictionary>? _exportersIndex; - public DependenciesTraversal(FilteredCatalog catalog, Func importFilter) + public DependenciesTraversal(FilteredCatalog catalog!!, Func importFilter!!) { - if (catalog == null) - { - throw new ArgumentNullException(nameof(catalog)); - } - - if (importFilter == null) - { - throw new ArgumentNullException(nameof(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 b949ec434338bc..872d99333ad7f8 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,17 +23,8 @@ internal sealed class DependentsTraversal : IComposablePartCatalogTraversal private readonly Func _importFilter; private Dictionary>? _importersIndex; - public DependentsTraversal(FilteredCatalog catalog, Func importFilter) + public DependentsTraversal(FilteredCatalog catalog!!, Func importFilter!!) { - if (catalog == null) - { - throw new ArgumentNullException(nameof(catalog)); - } - if (importFilter == null) - { - throw new ArgumentNullException(nameof(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 aaffa2ccc6feb1..8860f64133b478 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,13 +56,8 @@ public FilteredCatalog IncludeDependents(Func importFilt return Traverse(new DependentsTraversal(this, importFilter)); } - private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal) + private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal!!) { - if (traversal == null) - { - throw new ArgumentNullException(nameof(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 @@ -80,12 +75,8 @@ private FilteredCatalog Traverse(IComposablePartCatalogTraversal traversal) } } - private static HashSet GetTraversalClosure(IEnumerable parts, IComposablePartCatalogTraversal traversal) + private static HashSet GetTraversalClosure(IEnumerable parts, IComposablePartCatalogTraversal traversal!!) { - if (traversal == null) - { - throw new ArgumentNullException(nameof(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 9bd187f8899587..7ba75809e9f017 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,26 +25,16 @@ public EngineContext(ImportEngine importEngine, EngineContext? parentEngineConte _parentEngineContext = parentEngineContext; } - public void AddPartManager(PartManager part) + public void AddPartManager(PartManager part!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } - if (!_removedPartManagers.Remove(part)) { _addedPartManagers.Add(part); } } - public void RemovePartManager(PartManager part) + public void RemovePartManager(PartManager part!!) { - if (part == null) - { - throw new ArgumentNullException(nameof(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 36df11b809a622..57b215f82e16c4 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,12 +407,8 @@ 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) { - if (part == null) - { - throw new ArgumentNullException(nameof(part)); - } var result = CompositionResult.SucceededResult; // get out if the part is already composed @@ -686,13 +682,8 @@ private void StopSatisfyingImports(PartManager partManager, AtomicComposition? a return partManager; } - private EngineContext GetEngineContext(AtomicComposition atomicComposition) + private EngineContext GetEngineContext(AtomicComposition atomicComposition!!) { - if (atomicComposition == null) - { - throw new ArgumentNullException(nameof(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 17194f7b9bf6f1..c685134ded8a32 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,12 +30,8 @@ internal sealed class NonImportSourceImportDefinition : ContractBasedImportDefin private readonly ContractBasedImportDefinition _sourceDefinition; private IDictionary? _metadata; - public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition) + public NonImportSourceImportDefinition(ContractBasedImportDefinition sourceDefinition!!) { - if (sourceDefinition == null) - { - throw new ArgumentNullException(nameof(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 2a0d7eb1fc1ac0..8783ab01798697 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 @@ -281,13 +281,8 @@ private IEnumerable PartsInternal } } - internal override IEnumerable? GetCandidateParts(ImportDefinition definition) + internal override IEnumerable? GetCandidateParts(ImportDefinition definition!!) { - if (definition == null) - { - throw new ArgumentNullException(nameof(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 25d362e457d7d4..370486eb7fc55e 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,13 +26,8 @@ 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) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(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 b56a1695b12d7e..f8188f46572e97 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,13 +88,8 @@ private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical) return transparentProxyModuleBuilder; } - public static MetadataViewFactory GetMetadataViewFactory(Type viewType) + public static MetadataViewFactory GetMetadataViewFactory(Type viewType!!) { - if (viewType == null) - { - throw new ArgumentNullException(nameof(viewType)); - } - if (!viewType.IsInterface) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); @@ -137,12 +132,8 @@ public static MetadataViewFactory GetMetadataViewFactory(Type viewType) return metadataViewFactory!; } - public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory, IDictionary metadata) + public static TMetadataView CreateMetadataView(MetadataViewFactory metadataViewFactory!!, IDictionary metadata) { - if (metadataViewFactory == null) - { - throw new ArgumentNullException(nameof(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 c4514fdc9a8ad3..85f9431381fbd6 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,13 +12,8 @@ namespace System.ComponentModel.Composition { internal static class MetadataViewProvider { - public static TMetadataView GetMetadataView(IDictionary metadata) + public static TMetadataView GetMetadataView(IDictionary metadata!!) { - if (metadata == null) - { - throw new ArgumentNullException(nameof(metadata)); - } - Type metadataViewType = typeof(TMetadataView); // If the Metadata dictionary is cast compatible with the passed in type @@ -126,13 +121,8 @@ public static TMetadataView GetMetadataView(IDictionary GetPureGenericParameters(this Type type) + internal static IList GetPureGenericParameters(this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (type.IsGenericType && type.ContainsGenericParameters) { List pureGenericParameters = new List(); @@ -36,13 +31,8 @@ internal static IList GetPureGenericParameters(this Type type) } } - internal static int GetPureGenericArity(this Type type) + internal static int GetPureGenericArity(this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 fe017bf5bafb82..0cda1e03db94d7 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,23 +29,8 @@ 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!!) { - if (originalPartCreationInfo == null) - { - throw new ArgumentNullException(nameof(originalPartCreationInfo)); - } - - if (originalPart == null) - { - throw new ArgumentNullException(nameof(originalPart)); - } - - if (specialization == null) - { - throw new ArgumentNullException(nameof(specialization)); - } - _originalPartCreationInfo = originalPartCreationInfo; _originalPart = originalPart; _specialization = specialization; @@ -188,13 +173,8 @@ private void BuildTables() } } - private Dictionary BuildMembersTable(List members) + private Dictionary BuildMembersTable(List members!!) { - if (members == null) - { - throw new ArgumentNullException(nameof(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 cb4ea1ce43b35e..883d19802ab21b 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,13 +32,8 @@ private static Dictionary?> CastSingleValueCache } } - public ImportType(Type type, ImportCardinality cardinality) + public ImportType(Type type!!, ImportCardinality cardinality) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - _type = type; Type contractType = type; @@ -108,18 +103,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (baseType == null) - { - throw new ArgumentNullException(nameof(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 b47301619caaec..9212785003dbff 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,13 +12,8 @@ internal abstract class ImportingItem private readonly ContractBasedImportDefinition _definition; private readonly ImportType _importType; - protected ImportingItem(ContractBasedImportDefinition definition, ImportType importType) + protected ImportingItem(ContractBasedImportDefinition definition!!, ImportType importType) { - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - _definition = definition; _importType = importType; } @@ -45,13 +40,8 @@ public ImportType ImportType } } - private object CastExportsToCollectionImportType(Export[] exports) + private object CastExportsToCollectionImportType(Export[] exports!!) { - if (exports == null) - { - throw new ArgumentNullException(nameof(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); @@ -68,13 +58,8 @@ private object CastExportsToCollectionImportType(Export[] exports) return array; } - private object? CastExportsToSingleImportType(Export[] exports) + private object? CastExportsToSingleImportType(Export[] exports!!) { - if (exports == null) - { - throw new ArgumentNullException(nameof(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 b0c424d0855651..acf0f892b38438 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,14 +16,9 @@ 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) { - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - _member = member; } @@ -105,13 +100,8 @@ private void EnsureWritable() } } - private void SetCollectionMemberValue(object? instance, IEnumerable values) + private void SetCollectionMemberValue(object? instance, IEnumerable values!!) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } - ICollection? collection = null; Type? itemType = CollectionServices.GetCollectionElementType(ImportType.ActualType); if (itemType != null) @@ -123,13 +113,8 @@ private void SetCollectionMemberValue(object? instance, IEnumerable values) PopulateCollection(collection!, values); } - private ICollection GetNormalizedCollection(Type itemType, object? instance) + private ICollection GetNormalizedCollection(Type itemType!!, object? instance) { - if (itemType == null) - { - throw new ArgumentNullException(nameof(itemType)); - } - object? collectionObject = null; if (_member.CanRead) @@ -219,18 +204,8 @@ private void EnsureCollectionIsWritable(ICollection? collection) } } - private void PopulateCollection(ICollection collection, IEnumerable values) + private void PopulateCollection(ICollection collection!!, IEnumerable values!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - - if (values == null) - { - throw new ArgumentNullException(nameof(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 483f6bf6f0a37d..fa58b846c34b04 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,14 +15,10 @@ 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) { - if (productImportDefinition == null) - { - throw new ArgumentNullException(nameof(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 09452db87569f0..93280fa2bc2aca 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,14 +16,10 @@ 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) { - if (productImportDefinition == null) - { - throw new ArgumentNullException(nameof(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 7628378dc5f510..ceedd6c97bca0e 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,12 +21,8 @@ internal sealed class ReflectionComposablePartDefinition : ComposablePartDefinit private volatile ConstructorInfo? _constructor; private readonly object _lock = new object(); - public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo) + public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo!!) { - if (creationInfo == null) - { - throw new ArgumentNullException(nameof(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 144603f65ecf6a..4dc59dd2b64f60 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,13 +41,8 @@ public static ReflectionMember ToReflectionMember(this LazyMemberInfo lazyMember } } - public static LazyMemberInfo ToLazyMember(this MemberInfo member) + public static LazyMemberInfo ToLazyMember(this MemberInfo member!!) { - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - if (member.MemberType == MemberTypes.Property) { PropertyInfo? property = member as PropertyInfo; @@ -81,13 +76,8 @@ public static ReflectionWritableMember ToReflectionWriteableMember(this LazyMemb return reflectionMember; } - public static ReflectionProperty ToReflectionProperty(this PropertyInfo property) + public static ReflectionProperty ToReflectionProperty(this PropertyInfo property!!) { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } - return CreateReflectionProperty(property.GetGetMethod(true)!, property.GetSetMethod(true)!); } @@ -101,13 +91,8 @@ 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!!) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - return new ReflectionParameter(parameter); } @@ -121,33 +106,18 @@ 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!!) { - if (field == null) - { - throw new ArgumentNullException(nameof(field)); - } - return new ReflectionField(field); } - public static ReflectionType ToReflectionType(this Type type) + public static ReflectionType ToReflectionType(this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - return new ReflectionType(type); } - public static ReflectionWritableMember ToReflectionWritableMember(this MemberInfo member) + public static ReflectionWritableMember ToReflectionWritableMember(this MemberInfo member!!) { - if (member == null) - { - throw new ArgumentNullException(nameof(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 544227712ac350..81283f0f124bd7 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,13 +10,8 @@ internal sealed class ReflectionField : ReflectionWritableMember { private readonly FieldInfo _field; - public ReflectionField(FieldInfo field) + public ReflectionField(FieldInfo field!!) { - if (field == null) - { - throw new ArgumentNullException(nameof(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 0bf6f7f6b2cb4d..12a2a3af79b140 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,13 +14,8 @@ 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) { - if (exportDefinition == null) - { - throw new ArgumentNullException(nameof(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 20657c1d489376..8ea838bff2a591 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,11 +24,6 @@ public ReflectionMemberImportDefinition( ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, isRecomposable, isPrerequisite, requiredCreationPolicy, metadata, origin) { - if (contractName == null) - { - throw new ArgumentNullException(nameof(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 a869d34e539ced..9484b9ec86ffb1 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,13 +10,8 @@ internal sealed partial class ReflectionMethod : ReflectionMember { private readonly MethodInfo _method; - public ReflectionMethod(MethodInfo method) + public ReflectionMethod(MethodInfo method!!) { - if (method == null) - { - throw new ArgumentNullException(nameof(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 9fabe855f0911b..8719590128f726 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,18 +325,13 @@ 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) { - if (partType == null) - { - throw new ArgumentNullException(nameof(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 8124cfdf05b5fc..b7f7b9b6a6e168 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,13 +11,8 @@ internal sealed class ReflectionParameter : ReflectionItem { private readonly ParameterInfo _parameter; - public ReflectionParameter(ParameterInfo parameter) + public ReflectionParameter(ParameterInfo parameter!!) { - if (parameter == null) - { - throw new ArgumentNullException(nameof(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 0eb181feb9c26d..bb8241f9554f59 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,11 +24,6 @@ public ReflectionParameterImportDefinition( ICompositionElement? origin) : base(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, requiredCreationPolicy, metadata, origin) { - if (importingLazyParameter == null) - { - throw new ArgumentNullException(nameof(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 d06d87eb2525f2..9d3659fadf4c1d 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,13 +9,8 @@ internal sealed class ReflectionType : ReflectionMember { private readonly Type _type; - public ReflectionType(Type type) + public ReflectionType(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 1bdc9a906861cb..08105a1d139d87 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,13 +12,8 @@ namespace System.Composition.Diagnostics { internal static class CompositionTrace { - internal static void PartDefinitionResurrected(ComposablePartDefinition definition) + internal static void PartDefinitionResurrected(ComposablePartDefinition definition!!) { - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Rejection_DefinitionResurrected, @@ -27,19 +22,8 @@ internal static void PartDefinitionResurrected(ComposablePartDefinition definiti } } - internal static void PartDefinitionRejected(ComposablePartDefinition definition, ChangeRejectedException exception) + internal static void PartDefinitionRejected(ComposablePartDefinition definition!!, ChangeRejectedException exception!!) { - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } - - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - if (CompositionTraceSource.CanWriteWarning) { CompositionTraceSource.WriteWarning(CompositionTraceId.Rejection_DefinitionRejected, @@ -49,23 +33,8 @@ 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!!) { - if (catalog == null) - { - throw new ArgumentNullException(nameof(catalog)); - } - - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } - - if (fileName == null) - { - throw new ArgumentNullException(nameof(fileName)); - } - if (fileName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(fileName)), nameof(fileName)); @@ -81,13 +50,8 @@ internal static void AssemblyLoadFailed(DirectoryCatalog catalog, string fileNam } } - internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type) + internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute, @@ -96,18 +60,8 @@ internal static void DefinitionMarkedWithPartNotDiscoverableAttribute(Type type) } } - internal static void DefinitionMismatchedExportArity(Type type, MemberInfo member) + internal static void DefinitionMismatchedExportArity(Type type!!, MemberInfo member!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } - if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionMismatchedExportArity, @@ -116,13 +70,8 @@ internal static void DefinitionMismatchedExportArity(Type type, MemberInfo membe } } - internal static void DefinitionContainsNoExports(Type type) + internal static void DefinitionContainsNoExports(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (CompositionTraceSource.CanWriteInformation) { CompositionTraceSource.WriteInformation(CompositionTraceId.Discovery_DefinitionContainsNoExports, @@ -131,13 +80,8 @@ internal static void DefinitionContainsNoExports(Type type) } } - internal static void MemberMarkedWithMultipleImportAndImportMany(ReflectionItem item) + internal static void MemberMarkedWithMultipleImportAndImportMany(ReflectionItem item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(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 4f05d617239f2f..9543968fb86d16 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,18 +134,8 @@ 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) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } - - if (parameter == null) - { - throw new ArgumentNullException(nameof(parameter)); - } - requiredMetadataKey = null; requiredMetadataType = null; @@ -218,14 +208,9 @@ 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 { - if (constant == null) - { - throw new ArgumentNullException(nameof(constant)); - } - if (constant.Type == typeof(T) && constant.Value != null) { result = (T)constant.Value; diff --git a/src/libraries/System.ComponentModel.EventBasedAsync/src/Resources/Strings.resx b/src/libraries/System.ComponentModel.EventBasedAsync/src/Resources/Strings.resx index 86c96d308b8dd6..6ce9fbe442bfc8 100644 --- a/src/libraries/System.ComponentModel.EventBasedAsync/src/Resources/Strings.resx +++ b/src/libraries/System.ComponentModel.EventBasedAsync/src/Resources/Strings.resx @@ -57,9 +57,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - A non-null SendOrPostCallback must be supplied. - This operation has already had OperationCompleted called on it and further calls are illegal. @@ -78,4 +75,4 @@ This BackgroundWorker states that it doesn't support cancellation. Modify WorkerSupportsCancellation to state that it does support cancellation. - \ No newline at end of file + diff --git a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs index 8c90014be5d255..d008cab6819924 100644 --- a/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs +++ b/src/libraries/System.ComponentModel.EventBasedAsync/src/System/ComponentModel/AsyncOperation.cs @@ -64,7 +64,7 @@ public void OperationCompleted() private void PostCore(SendOrPostCallback d, object? arg, bool markCompleted) { VerifyNotCompleted(); - VerifyDelegateNotNull(d); + ArgumentNullException.ThrowIfNull(d); if (markCompleted) { // This call is in response to a PostOperationCompleted. As such, we need to mark @@ -96,14 +96,6 @@ private void VerifyNotCompleted() } } - private void VerifyDelegateNotNull(SendOrPostCallback d) - { - if (d == null) - { - throw new ArgumentNullException(nameof(d), SR.Async_NullDelegate); - } - } - /// /// Only for use by AsyncOperationManager to create new AsyncOperation objects /// 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 91f604aa7a46f1..2082564bbffaff 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,17 +16,8 @@ public sealed class DesignerSerializerAttribute : Attribute /// /// Creates a new designer serialization attribute. /// - public DesignerSerializerAttribute(Type serializerType, Type baseSerializerType) + public DesignerSerializerAttribute(Type serializerType!!, Type baseSerializerType!!) { - if (serializerType == null) - { - throw new ArgumentNullException(nameof(serializerType)); - } - if (baseSerializerType == null) - { - throw new ArgumentNullException(nameof(baseSerializerType)); - } - SerializerTypeName = serializerType.AssemblyQualifiedName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; } @@ -34,13 +25,8 @@ public DesignerSerializerAttribute(Type serializerType, Type baseSerializerType) /// /// Creates a new designer serialization attribute. /// - public DesignerSerializerAttribute(string? serializerTypeName, Type baseSerializerType) + public DesignerSerializerAttribute(string? serializerTypeName, Type baseSerializerType!!) { - if (baseSerializerType == null) - { - throw new ArgumentNullException(nameof(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 51472cdeed5b6b..b78fb24b15721a 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/DesignerAttribute.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/DesignerAttribute.cs @@ -17,9 +17,9 @@ 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!!) { - DesignerTypeName = designerTypeName ?? throw new ArgumentNullException(nameof(designerTypeName)); + DesignerTypeName = designerTypeName; DesignerBaseTypeName = "System.ComponentModel.Design.IDesigner, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } @@ -27,13 +27,8 @@ 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!!) { - if (designerType == null) - { - throw new ArgumentNullException(nameof(designerType)); - } - DesignerTypeName = designerType.AssemblyQualifiedName!; DesignerBaseTypeName = "System.ComponentModel.Design.IDesigner, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } @@ -43,10 +38,10 @@ 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) { - DesignerTypeName = designerTypeName ?? throw new ArgumentNullException(nameof(designerTypeName)); + DesignerTypeName = designerTypeName; DesignerBaseTypeName = designerBaseTypeName; } @@ -55,18 +50,9 @@ 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!!) { - if (designerTypeName == null) - { - throw new ArgumentNullException(nameof(designerTypeName)); - } - if (designerBaseType == null) - { - throw new ArgumentNullException(nameof(designerBaseType)); - } - DesignerTypeName = designerTypeName; DesignerBaseTypeName = designerBaseType.AssemblyQualifiedName!; } @@ -76,18 +62,9 @@ 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!!) { - if (designerType == null) - { - throw new ArgumentNullException(nameof(designerType)); - } - if (designerBaseType == null) - { - throw new ArgumentNullException(nameof(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 ce23595bc2b1cb..6addfb6f065dea 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EditorAttribute.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EditorAttribute.cs @@ -28,10 +28,10 @@ public EditorAttribute() /// name of the editor. /// public EditorAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string typeName!!, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string? baseTypeName) { - EditorTypeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); + EditorTypeName = typeName; EditorBaseTypeName = baseTypeName; } @@ -39,18 +39,9 @@ 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!!) { - if (typeName == null) - { - throw new ArgumentNullException(nameof(typeName)); - } - if (baseType == null) - { - throw new ArgumentNullException(nameof(baseType)); - } - EditorTypeName = typeName; EditorBaseTypeName = baseType.AssemblyQualifiedName; } @@ -59,18 +50,9 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (baseType == null) - { - throw new ArgumentNullException(nameof(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 54e01530a48ad4..40bd1c903b01f0 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/EventHandlerList.cs @@ -69,13 +69,8 @@ public void AddHandler(object key, Delegate? value) } } - public void AddHandlers(EventHandlerList listToAddFrom) + public void AddHandlers(EventHandlerList listToAddFrom!!) { - if (listToAddFrom == null) - { - throw new ArgumentNullException(nameof(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 bd24fd3129c8d8..da48222cbfcba1 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/InvalidEnumArgumentException.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/InvalidEnumArgumentException.cs @@ -43,16 +43,12 @@ 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) { - if (enumClass == null) - { - throw new ArgumentNullException(nameof(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 102ca666d2e444..c8920bb7c00f3e 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,12 +500,8 @@ 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) { - if (func == null) - throw new ArgumentNullException(nameof(func)); - if (element == null) - throw new ArgumentNullException(nameof(element)); _func = func; this.element = element; this.name = name; @@ -546,12 +542,8 @@ 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) { - if (func == null) - throw new ArgumentNullException(nameof(func)); - if (element == null) - throw new ArgumentNullException(nameof(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 934475456098a5..a2c531ea43ae1e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeCollection.cs @@ -46,10 +46,7 @@ public AttributeCollection(params Attribute[]? attributes) for (int idx = 0; idx < _attributes.Length; idx++) { - if (_attributes[idx] == null) - { - throw new ArgumentNullException(nameof(attributes)); - } + ArgumentNullException.ThrowIfNull(_attributes[idx], nameof(attributes)); } } @@ -60,13 +57,8 @@ 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) { - if (existing == null) - { - throw new ArgumentNullException(nameof(existing)); - } - if (newAttributes == null) { newAttributes = Array.Empty(); @@ -78,10 +70,7 @@ public static AttributeCollection FromExisting(AttributeCollection existing, par for (int idx = 0; idx < newAttributes.Length; idx++) { - if (newAttributes[idx] == null) - { - throw new ArgumentNullException(nameof(newAttributes)); - } + ArgumentNullException.ThrowIfNull(newAttributes[idx], nameof(newAttributes)); // We must see if this attribute is already in the existing // array. If it is, we replace it. @@ -135,15 +124,10 @@ public static AttributeCollection FromExisting(AttributeCollection existing, par /// /// 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 { - if (attributeType == null) - { - throw new ArgumentNullException(nameof(attributeType)); - } - lock (s_internalSyncObject) { // 2 passes here for perf. Really! first pass, we just @@ -257,13 +241,8 @@ 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!!) { - if (attributeType == null) - { - throw new ArgumentNullException(nameof(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 69e13363d62a56..3c9f22c6572dbe 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/AttributeProviderAttribute.cs @@ -13,30 +13,25 @@ public class AttributeProviderAttribute : Attribute /// /// Creates a new AttributeProviderAttribute object. /// - public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName) + public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName!!) { - TypeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); + TypeName = typeName; } /// /// Creates a new AttributeProviderAttribute object. /// - public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName, string propertyName) + public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] string typeName!!, string propertyName!!) { - TypeName = typeName ?? throw new ArgumentNullException(nameof(typeName)); - PropertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); + TypeName = typeName; + PropertyName = propertyName; } /// /// Creates a new AttributeProviderAttribute object. /// - public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] Type type) + public AttributeProviderAttribute([DynamicallyAccessedMembers(RequiredMemberTypes)] Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 24158ec5b2c853..0cc31005ea0549 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs @@ -89,13 +89,8 @@ 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 945a723d1b6e7b..43f50d8fbed301 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs @@ -63,16 +63,8 @@ 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) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (objectName == null) - { - throw new ArgumentNullException(nameof(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 9449116e8cad81..3617a233e79bca 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs @@ -217,13 +217,8 @@ 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) { - if (component == null) - { - throw new ArgumentNullException(nameof(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 3e8408548c63a0..16f64850b08078 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/CultureInfoConverter.cs @@ -29,13 +29,8 @@ public class CultureInfoConverter : TypeConverter /// /// Retrieves the Name for a input CultureInfo. /// - protected virtual string GetCultureName(CultureInfo culture) + protected virtual string GetCultureName(CultureInfo culture!!) { - if (culture == null) - { - throw new ArgumentNullException(nameof(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 df182f2dff24d9..b39b1b67472e3f 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,18 +32,8 @@ 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) { - if (parent == null) - { - throw new ArgumentNullException(nameof(parent)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length"), nameof(name)); @@ -57,18 +47,8 @@ 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!!) { - if (pageName == null) - { - throw new ArgumentNullException(nameof(pageName)); - } - - if (valueName == null) - { - throw new ArgumentNullException(nameof(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 fcd934ab68b83c..b22b655bf28922 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,26 +21,16 @@ public DesignerVerb? this[int index] public int Add(DesignerVerb? value) => List.Add(value); - public void AddRange(DesignerVerb?[] value) + public void AddRange(DesignerVerb?[] value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(DesignerVerbCollection value) + public void AddRange(DesignerVerbCollection value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 eb5f0d456b8cd3..1da32e75bb553e 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,13 +30,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 460ec9b91d2f59..1179fc405b1fbb 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,21 +59,16 @@ public HelpKeywordAttribute() /// /// Creates a HelpKeywordAttribute with the value being the given keyword string. /// - public HelpKeywordAttribute(string keyword) + public HelpKeywordAttribute(string keyword!!) { - HelpKeyword = keyword ?? throw new ArgumentNullException(nameof(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!!) { - if (t == null) - { - throw new ArgumentNullException(nameof(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 2e7841929e1540..094b144381a349 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,15 +66,10 @@ 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 { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (_contextStack != null) { int level = _contextStack.Count; @@ -99,13 +94,8 @@ 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!!) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (_contextStack == null) { _contextStack = new ArrayList(); @@ -134,13 +124,8 @@ public void Append(object context) /// /// Pushes the given object onto the stack. /// - public void Push(object context) + public void Push(object context!!) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if (_contextStack == null) { _contextStack = new ArrayList(); 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 c1c610a1bb28f1..060ad08d616df5 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,26 +16,16 @@ public sealed class DefaultSerializationProviderAttribute : Attribute /// /// Creates a new DefaultSerializationProviderAttribute /// - public DefaultSerializationProviderAttribute(Type providerType) + public DefaultSerializationProviderAttribute(Type providerType!!) { - if (providerType == null) - { - throw new ArgumentNullException(nameof(providerType)); - } - ProviderTypeName = providerType.AssemblyQualifiedName!; } /// /// Creates a new DefaultSerializationProviderAttribute /// - public DefaultSerializationProviderAttribute(string providerTypeName) + public DefaultSerializationProviderAttribute(string providerTypeName!!) { - if (providerTypeName == null) - { - throw new ArgumentNullException(nameof(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 090fa91accbf7c..54f7abcd9cfeb5 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,32 +69,14 @@ 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 { - if (sourceOwner == null) - { - throw new ArgumentNullException(nameof(sourceOwner)); - } - if (sourceMember == null) - { - throw new ArgumentNullException(nameof(sourceMember)); - } - return GetRelationship(new MemberRelationship(sourceOwner, sourceMember)); } set { - if (sourceOwner == null) - { - throw new ArgumentNullException(nameof(sourceOwner)); - } - if (sourceMember == null) - { - throw new ArgumentNullException(nameof(sourceMember)); - } - SetRelationship(new MemberRelationship(sourceOwner, sourceMember), value); } } @@ -197,10 +179,10 @@ public bool Equals(RelationshipEntry other) /// /// Creates a new member relationship. /// - public MemberRelationship(object owner, MemberDescriptor member) + public MemberRelationship(object owner!!, MemberDescriptor member!!) { - Owner = owner ?? throw new ArgumentNullException(nameof(owner)); - Member = member ?? throw new ArgumentNullException(nameof(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 f9b7d358911b9e..c22454c9d84b66 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,17 +17,8 @@ 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) { - if (serializerType == null) - { - throw new ArgumentNullException(nameof(serializerType)); - } - if (baseSerializerType == null) - { - throw new ArgumentNullException(nameof(baseSerializerType)); - } - SerializerTypeName = serializerType.AssemblyQualifiedName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; Reloadable = reloadable; @@ -36,13 +27,8 @@ public RootDesignerSerializerAttribute(Type serializerType, Type baseSerializerT /// /// Creates a new designer serialization attribute. /// - public RootDesignerSerializerAttribute(string serializerTypeName, Type baseSerializerType, bool reloadable) + public RootDesignerSerializerAttribute(string serializerTypeName, Type baseSerializerType!!, bool reloadable) { - if (baseSerializerType == null) - { - throw new ArgumentNullException(nameof(baseSerializerType)); - } - SerializerTypeName = serializerTypeName; SerializerBaseTypeName = baseSerializerType.AssemblyQualifiedName; Reloadable = reloadable; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs index 116bbf564c0265..3077865a5f5adc 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/ServiceContainer.cs @@ -233,10 +233,7 @@ public virtual void RemoveService(Type serviceType, bool promote) } // We're going to remove this from our local list. - if (serviceType == null) - { - throw new ArgumentNullException(nameof(serviceType)); - } + ArgumentNullException.ThrowIfNull(serviceType); Services.Remove(serviceType); } 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 c043cdd6e1011b..aae303fab6b605 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EnumConverter.cs @@ -115,13 +115,8 @@ 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 79ae3633528f87..508c394d9a13f0 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/InstallerTypeAttribute.cs @@ -17,13 +17,8 @@ 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!!) { - if (installerType == null) - { - throw new ArgumentNullException(nameof(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 5810df7258e5fc..7fef5ef5ccaa7a 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -882,13 +882,8 @@ 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - testPosition = LastAssignedPosition + 1; if (input.Length == 0) // nothing to add. @@ -1258,13 +1253,8 @@ 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (position < 0 || position >= _testString.Length) { testPosition = position; @@ -1819,13 +1809,8 @@ 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (position < 0 || position >= _testString.Length) { testPosition = position; @@ -1858,13 +1843,8 @@ public bool Replace(string input, int position, out int testPosition, out Masked /// 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (endPosition >= _testString.Length) { testPosition = endPosition; @@ -2044,13 +2024,8 @@ 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(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 3d419bf44a7ac2..7bace2d4e7ecbe 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs @@ -38,12 +38,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.InvalidMemberName, nameof(name)); @@ -65,13 +61,8 @@ protected MemberDescriptor(string name, Attribute[]? attributes) /// /// Initializes a new instance of the class with the specified . /// - protected MemberDescriptor(MemberDescriptor descr) + protected MemberDescriptor(MemberDescriptor descr!!) { - if (descr == null) - { - throw new ArgumentNullException(nameof(descr)); - } - _name = descr.Name; _displayName = _name; _nameHash = _name?.GetHashCode() ?? 0; @@ -89,13 +80,8 @@ 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) { - if (oldMemberDescriptor == null) - { - throw new ArgumentNullException(nameof(oldMemberDescriptor)); - } - _name = oldMemberDescriptor.Name; _displayName = oldMemberDescriptor.DisplayName; _nameHash = _name.GetHashCode(); @@ -316,13 +302,8 @@ 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!!) { - if (attributeList == null) - { - throw new ArgumentNullException(nameof(attributeList)); - } - if (_originalAttributes != null) { foreach (Attribute attr in _originalAttributes) @@ -406,17 +387,12 @@ 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) { - if (componentClass == null) - { - throw new ArgumentNullException(nameof(componentClass)); - } - MethodInfo? result; if (publicOnly) { @@ -445,18 +421,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return TypeDescriptor.GetAssociation(type, instance); } @@ -466,19 +432,8 @@ 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!!) { - - if (componentClass == null) - { - throw new ArgumentNullException(nameof(componentClass)); - } - - if (component == null) - { - throw new ArgumentNullException(nameof(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 656191ebfaffcb..62275414eaa2ef 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MultilineStringConverter.cs @@ -14,13 +14,8 @@ 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 87728cf2c6b961..d443705fc6d315 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NestedContainer.cs @@ -18,9 +18,9 @@ public class NestedContainer : Container, INestedContainer /// /// Creates a new NestedContainer. /// - public NestedContainer(IComponent owner) + public NestedContainer(IComponent owner!!) { - Owner = owner ?? throw new ArgumentNullException(nameof(owner)); + Owner = owner; Owner.Disposed += new EventHandler(OnOwnerDisposed); } @@ -59,12 +59,8 @@ 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) { - if (component == null) - { - throw new ArgumentNullException(nameof(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 e0a06176054ebc..d59ceab099e5e2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/NullableConverter.cs @@ -97,13 +97,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 9ffaaa702da168..09e7039aa8afa9 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs @@ -121,17 +121,8 @@ 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!!) { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - if (_valueChangedHandlers == null) { _valueChangedHandlers = new Hashtable(); @@ -399,17 +390,8 @@ 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!!) { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - if (_valueChangedHandlers != null) { EventHandler? h = (EventHandler?)_valueChangedHandlers[component]; 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 4f49461af5c373..639e76d3538317 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ProvidePropertyAttribute.cs @@ -16,13 +16,8 @@ public sealed class ProvidePropertyAttribute : Attribute /// public ProvidePropertyAttribute( string propertyName, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type receiverType) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type receiverType!!) { - if (receiverType == null) - { - throw new ArgumentNullException(nameof(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 ec1987b77bb451..e5a11634c6e7bc 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs @@ -481,17 +481,8 @@ 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!!) { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - if (handler == null) - { - throw new ArgumentNullException(nameof(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 2e694467f8465f..e4ff7e40f2cb60 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -228,18 +228,9 @@ 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) { - if (editorBaseType == null) - { - throw new ArgumentNullException(nameof(editorBaseType)); - } - - if (table == null) - { - Debug.Fail("COMPAT: Editor table should not be null"); - // don't throw; RTM didn't so we can't do it either. - } + 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) { @@ -628,13 +619,8 @@ internal PropertyDescriptorCollection GetExtendedProperties(object instance) return properties; } - protected internal override IExtenderProvider[] GetExtenderProviders(object instance) + protected internal override IExtenderProvider[] GetExtenderProviders(object instance!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(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 f974e4f2275140..d86d57cd0c198c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemAttribute.cs @@ -46,21 +46,16 @@ 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!!) { - _toolboxItemTypeName = toolboxItemTypeName ?? throw new ArgumentNullException(nameof(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!!) { - if (toolboxItemType == null) - { - throw new ArgumentNullException(nameof(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 f19dff841be888..2a40510c67ff29 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeConverter.cs @@ -110,13 +110,8 @@ public virtual bool CanConvertTo(ITypeDescriptorContext? context, Type? destinat /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 ce66028a1acf7d..deb02e1689b910 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptionProvider.cs @@ -61,10 +61,7 @@ protected TypeDescriptionProvider(TypeDescriptionProvider parent) return _parent.CreateInstance(provider, objectType, argTypes, args); } - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } + ArgumentNullException.ThrowIfNull(objectType); return Activator.CreateInstance(objectType, args); } @@ -114,10 +111,7 @@ protected internal virtual IExtenderProvider[] GetExtenderProviders(object insta return _parent.GetExtenderProviders(instance); } - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } + ArgumentNullException.ThrowIfNull(instance); return Array.Empty(); } @@ -160,13 +154,8 @@ 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return GetReflectionType(instance.GetType(), instance); } @@ -205,10 +194,7 @@ public virtual Type GetRuntimeType(Type reflectionType) return _parent.GetRuntimeType(reflectionType); } - if (reflectionType == null) - { - throw new ArgumentNullException(nameof(reflectionType)); - } + ArgumentNullException.ThrowIfNull(reflectionType); if (reflectionType.GetType().Assembly == typeof(object).Assembly) { @@ -240,13 +226,8 @@ 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return GetTypeDescriptor(instance.GetType(), instance); } @@ -278,13 +259,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 ded2068999cc5c..9fb2c5a8c34913 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -114,18 +114,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } - TypeDescriptionProvider existingProvider = GetProvider(type); TypeDescriptionProvider provider = new AttributeProvider(existingProvider, attributes); TypeDescriptor.AddProvider(provider, type); @@ -143,18 +133,8 @@ public static TypeDescriptionProvider AddAttributes(Type type, params Attribute[ /// 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } - TypeDescriptionProvider existingProvider = GetProvider(instance); TypeDescriptionProvider provider = new AttributeProvider(existingProvider, attributes); AddProvider(provider, instance); @@ -184,18 +164,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - lock (s_providerTable) { // Get the root node, hook it up, and stuff it back into @@ -217,17 +187,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } bool refreshNeeded; // Get the root node, hook it up, and stuff it back into @@ -257,18 +218,8 @@ public static void AddProvider(TypeDescriptionProvider provider, object instance /// all types. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void AddProviderTransparent(TypeDescriptionProvider provider, Type type) + public static void AddProviderTransparent(TypeDescriptionProvider provider!!, Type type!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - AddProvider(provider, type); } @@ -280,18 +231,8 @@ public static void AddProviderTransparent(TypeDescriptionProvider provider, Type /// the object from finalizing. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void AddProviderTransparent(TypeDescriptionProvider provider, object instance) + public static void AddProviderTransparent(TypeDescriptionProvider provider!!, object instance!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - AddProvider(provider, instance); } @@ -360,18 +301,8 @@ 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!!) { - if (primary == null) - { - throw new ArgumentNullException(nameof(primary)); - } - - if (secondary == null) - { - throw new ArgumentNullException(nameof(secondary)); - } - if (primary == secondary) { throw new ArgumentException(SR.TypeDescriptorSameAssociation); @@ -441,21 +372,13 @@ public static EventDescriptor CreateEvent( /// public static object? CreateInstance( IServiceProvider? provider, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType!!, Type[]? argTypes, object[]? args) { - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } - if (argTypes != null) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(args); if (argTypes.Length != args.Length) { @@ -575,18 +498,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (primary == null) - { - throw new ArgumentNullException(nameof(primary)); - } - object associatedObject = primary; if (!type.IsInstanceOfType(primary)) @@ -924,14 +837,9 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(typeName); - } - return NodeFor(type).GetTypeDescriptor(type); } @@ -989,13 +897,8 @@ 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) { - if (editorBaseType == null) - { - throw new ArgumentNullException(nameof(editorBaseType)); - } - return GetDescriptor(component, noCustomTypeDesc)!.GetEditor(editorBaseType); } @@ -1005,13 +908,8 @@ internal static ICustomTypeDescriptor GetExtendedDescriptor(object component) [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] public static object? GetEditor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, - Type editorBaseType) + Type editorBaseType!!) { - if (editorBaseType == null) - { - throw new ArgumentNullException(nameof(editorBaseType)); - } - return GetDescriptor(type, nameof(type))!.GetEditor(editorBaseType); } @@ -1222,13 +1120,8 @@ 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!!) { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - return GetProvider(component).GetFullComponentName(component); } @@ -1430,13 +1323,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - return NodeFor(type, true); } @@ -1448,13 +1336,8 @@ 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return NodeFor(instance, true); } @@ -1475,13 +1358,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - return NodeFor(type).GetReflectionType(type); } @@ -1490,13 +1368,8 @@ 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return NodeFor(instance).GetReflectionType(instance); } @@ -2479,18 +2352,8 @@ 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!!) { - if (primary == null) - { - throw new ArgumentNullException(nameof(primary)); - } - - if (secondary == null) - { - throw new ArgumentNullException(nameof(secondary)); - } - Hashtable assocTable = AssociationTable; IList? associations = (IList?)assocTable?[primary]; if (associations != null) @@ -2516,13 +2379,8 @@ 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!!) { - if (primary == null) - { - throw new ArgumentNullException(nameof(primary)); - } - Hashtable assocTable = AssociationTable; assocTable?.Remove(primary); } @@ -2534,18 +2392,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - // Walk the nodes until we find the right one, and then remove it. NodeRemove(type, provider); RaiseRefresh(type); @@ -2558,18 +2406,8 @@ 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!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - // Walk the nodes until we find the right one, and then remove it. NodeRemove(instance, provider); RaiseRefresh(instance); @@ -2583,18 +2421,8 @@ public static void RemoveProvider(TypeDescriptionProvider provider, object insta /// associated with. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveProviderTransparent(TypeDescriptionProvider provider, Type type) + public static void RemoveProviderTransparent(TypeDescriptionProvider provider!!, Type type!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - RemoveProvider(provider, type); } @@ -2605,18 +2433,8 @@ public static void RemoveProviderTransparent(TypeDescriptionProvider provider, T /// associated with. /// [EditorBrowsable(EditorBrowsableState.Advanced)] - public static void RemoveProviderTransparent(TypeDescriptionProvider provider, object instance) + public static void RemoveProviderTransparent(TypeDescriptionProvider provider!!, object instance!!) { - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - RemoveProvider(provider, instance); } @@ -2648,13 +2466,8 @@ 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!!) { - if (infos == null) - { - throw new ArgumentNullException(nameof(infos)); - } - ArrayList.Adapter(infos).Sort(MemberDescriptorComparer.Instance); } @@ -2681,13 +2494,8 @@ 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) { - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } - if (instance == null) { return null; @@ -3055,13 +2863,8 @@ TypeConverter ICustomTypeDescriptor.GetConverter() /// ICustomTypeDescriptor implementation. /// [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType!!) { - if (editorBaseType == null) - { - throw new ArgumentNullException(nameof(editorBaseType)); - } - object? editor = _primary.GetEditor(editorBaseType) ?? _secondary.GetEditor(editorBaseType); return editor; @@ -3155,21 +2958,13 @@ internal TypeDescriptionNode(TypeDescriptionProvider provider) /// public override object? CreateInstance( IServiceProvider? provider, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type objectType!!, Type[]? argTypes, object[]? args) { - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } - if (argTypes != null) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(args); if (argTypes.Length != args.Length) { @@ -3184,13 +2979,8 @@ 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return Provider.GetCache(instance); } @@ -3199,23 +2989,13 @@ 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!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return new DefaultExtendedTypeDescriptor(this, instance); } - protected internal override IExtenderProvider[] GetExtenderProviders(object instance) + protected internal override IExtenderProvider[] GetExtenderProviders(object instance!!) { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - return Provider.GetExtenderProviders(instance); } @@ -3229,13 +3009,8 @@ 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!!) { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } - return Provider.GetFullComponentName(component); } @@ -3245,24 +3020,14 @@ protected internal override IExtenderProvider[] GetExtenderProviders(object inst /// [return: DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] public override Type GetReflectionType( - [DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] Type objectType, + [DynamicallyAccessedMembers(ReflectTypesDynamicallyAccessedMembers)] Type objectType!!, object? instance) { - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } - return Provider.GetReflectionType(objectType, instance); } - public override Type GetRuntimeType(Type objectType) + public override Type GetRuntimeType(Type objectType!!) { - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } - return Provider.GetRuntimeType(objectType); } @@ -3270,13 +3035,8 @@ 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) { - if (objectType == null) - { - throw new ArgumentNullException(nameof(objectType)); - } - if (instance != null && !objectType.IsInstanceOfType(instance)) { throw new ArgumentException(nameof(instance)); @@ -3285,12 +3045,8 @@ public override ICustomTypeDescriptor GetTypeDescriptor([DynamicallyAccessedMemb return new DefaultTypeDescriptor(this, objectType, instance); } - public override bool IsSupportedType(Type type) + public override bool IsSupportedType(Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return Provider.IsSupportedType(type); } @@ -3447,13 +3203,8 @@ TypeConverter ICustomTypeDescriptor.GetConverter() /// ICustomTypeDescriptor implementation. /// [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType!!) { - if (editorBaseType == null) - { - throw new ArgumentNullException(nameof(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 @@ -3774,13 +3525,8 @@ TypeConverter ICustomTypeDescriptor.GetConverter() /// ICustomTypeDescriptor implementation. /// [RequiresUnreferencedCode(EditorRequiresUnreferencedCode)] - object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType!!) { - if (editorBaseType == null) - { - throw new ArgumentNullException(nameof(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 779fc781923167..96a75b59aaee28 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs @@ -64,13 +64,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 b11bf810aafd59..b594d47fd0c5eb 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs @@ -61,13 +61,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 616de8a7895c86..1c2361ebc54d68 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/VersionConverter.cs @@ -62,13 +62,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 c3c83605400e0e..5b43217751826b 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs @@ -45,13 +45,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 7bf0030eccdda5..56b0817af3433e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/PointConverter.cs @@ -61,13 +61,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } - if (value is Point pt) { if (destinationType == typeof(string)) @@ -101,13 +96,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) { - if (propertyValues == null) - { - throw new ArgumentNullException(nameof(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 9c0393da53ab33..ebb96371a95f45 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/RectangleConverter.cs @@ -59,13 +59,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } - if (value is Rectangle rect) { if (destinationType == typeof(string)) @@ -104,13 +99,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) { - if (propertyValues == null) - { - throw new ArgumentNullException(nameof(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 b19113721a455e..aa15f5c416bc0e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeConverter.cs @@ -59,13 +59,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } - if (value is Size size) { if (destinationType == typeof(string)) @@ -99,13 +94,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) { - if (propertyValues == null) - { - throw new ArgumentNullException(nameof(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 c48c0f4cd6698d..6db51a7530a517 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/SizeFConverter.cs @@ -58,13 +58,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } - if (value is SizeF size) { if (destinationType == typeof(string)) @@ -96,13 +91,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina return base.ConvertTo(context, culture, value, destinationType); } - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) { - if (propertyValues == null) - { - throw new ArgumentNullException(nameof(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 5564909ab1b90e..70c45e8aff1bcd 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 ?? throw new ArgumentNullException(nameof(name)); + Name = 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 e3f93414c4fa42..2ab60b99bbb8be 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 ?? throw new ArgumentNullException(nameof(sharingBoundaryNames)); + _sharingBoundaryNames = 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 738aa29a48d0be..c1185c2413b2d1 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,13 +45,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(type)); - } - var partBuilder = new PartConventionBuilder((t) => IsDescendentOf(t, type)); _conventions.Add(partBuilder); return partBuilder; @@ -74,13 +69,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(type)); - } - var partBuilder = new PartConventionBuilder((t) => t == type); _conventions.Add(partBuilder); return partBuilder; @@ -93,13 +83,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(typeFilter)); - } - var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; @@ -111,13 +96,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(typeFilter)); - } - var partBuilder = new PartConventionBuilder(typeFilter); _conventions.Add(partBuilder); return partBuilder; @@ -156,13 +136,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(member)); - } - // Now edit the attributes returned from the base type List cachedAttributes = null; var typeInfo = member as TypeInfo; @@ -296,13 +271,8 @@ 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 == 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 d460de83e2bfe0..a0bcdf7fe06a05 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,9 +38,9 @@ public ExportConventionBuilder AsContractType() /// /// The contract type. /// An export builder allowing further configuration. - public ExportConventionBuilder AsContractType(Type type) + public ExportConventionBuilder AsContractType(Type type!!) { - _contractType = type ?? throw new ArgumentNullException(nameof(type)); + _contractType = type; return this; } @@ -49,12 +49,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(contractName)); - } if (contractName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(contractName)), nameof(contractName)); @@ -68,9 +64,9 @@ 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!!) { - _getContractNameFromPartType = getContractNameFromPartType ?? throw new ArgumentNullException(nameof(getContractNameFromPartType)); + _getContractNameFromPartType = getContractNameFromPartType; return this; } @@ -80,13 +76,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); @@ -105,22 +96,13 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (getValueFromPartType == null) - { - throw new ArgumentNullException(nameof(getValueFromPartType)); - } - if (_metadataItemFuncs == null) { _metadataItemFuncs = new List>>(); 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 cbf0a1a54285e7..fef34353fb59be 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,12 +28,8 @@ internal ImportConventionBuilder() { } /// /// /// An import builder allowing further configuration. - public ImportConventionBuilder AsContractName(string contractName) + public ImportConventionBuilder AsContractName(string contractName!!) { - if (contractName == null) - { - throw new ArgumentNullException(nameof(contractName)); - } if (contractName.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(contractName)), nameof(contractName)); @@ -47,9 +43,9 @@ 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!!) { - _getContractNameFromPartType = getContractNameFromPartType ?? throw new ArgumentNullException(nameof(getContractNameFromPartType)); + _getContractNameFromPartType = getContractNameFromPartType; return this; } @@ -90,12 +86,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); @@ -114,22 +106,13 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (getConstraintValueFromPartType == null) - { - throw new ArgumentNullException(nameof(getConstraintValueFromPartType)); - } - if (_metadataConstraintItemFuncs == null) { _metadataConstraintItemFuncs = new List>>(); 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 8fbfd3d51ec4e4..151514d539203d 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 @@ -65,13 +65,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } - var exportBuilder = new ExportConventionBuilder(); exportConfiguration(exportBuilder); _typeExportBuilders.Add(exportBuilder); @@ -94,13 +89,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } - ExportConventionBuilder exportBuilder = new ExportConventionBuilder().AsContractType(); exportConfiguration(exportBuilder); _typeExportBuilders.Add(exportBuilder); @@ -112,9 +102,9 @@ 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!!) { - _constructorFilter = constructorSelector ?? throw new ArgumentNullException(nameof(constructorSelector)); + _constructorFilter = constructorSelector; return this; } @@ -125,9 +115,9 @@ 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!!) { - _configureConstuctorImports = importConfiguration ?? throw new ArgumentNullException(nameof(importConfiguration)); + _configureConstuctorImports = importConfiguration; SelectConstructor(constructorSelector); return this; } @@ -137,13 +127,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(interfaceFilter)); - } - return ExportInterfacesImpl(interfaceFilter, null); } @@ -162,19 +147,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(interfaceFilter)); - } - - if (exportConfiguration == null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } - return ExportInterfacesImpl(interfaceFilter, exportConfiguration); } @@ -190,13 +165,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - return ExportPropertiesImpl(propertyFilter, null); } @@ -206,19 +176,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - - if (exportConfiguration == null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } - return ExportPropertiesImpl(propertyFilter, exportConfiguration); } @@ -235,13 +195,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - return ExportPropertiesImpl(propertyFilter, null); } @@ -252,19 +207,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - - if (exportConfiguration == null) - { - throw new ArgumentNullException(nameof(exportConfiguration)); - } - return ExportPropertiesImpl(propertyFilter, exportConfiguration); } @@ -280,13 +225,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - return ImportPropertiesImpl(propertyFilter, null); } @@ -296,19 +236,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - - if (importConfiguration == null) - { - throw new ArgumentNullException(nameof(importConfiguration)); - } - return ImportPropertiesImpl(propertyFilter, importConfiguration); } @@ -325,13 +255,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - return ImportPropertiesImpl(propertyFilter, null); } @@ -342,19 +267,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyFilter)); - } - - if (importConfiguration == null) - { - throw new ArgumentNullException(nameof(importConfiguration)); - } - return ImportPropertiesImpl(propertyFilter, importConfiguration); } @@ -390,13 +305,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(sharingBoundary)); - } - if (sharingBoundary.Length == 0) { throw new ArgumentException(SR.ArgumentException_EmptyString); @@ -418,12 +328,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); @@ -443,22 +349,13 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, nameof(name)), nameof(name)); } - if (getValueFromPartType == null) - { - throw new ArgumentNullException(nameof(getValueFromPartType)); - } - if (_metadataItemFuncs == null) { _metadataItemFuncs = new List>>(); 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 717acbefec684a..0dd3993734a21e 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,13 +27,8 @@ public bool VerifyMethodInfo(MethodInfo mi) return mi == _methodInfo; } - private static MethodInfo SelectMethods(Expression> methodSelector) + private static MethodInfo SelectMethods(Expression> methodSelector!!) { - if (methodSelector == null) - { - throw new ArgumentNullException(nameof(methodSelector)); - } - Expression expr = Reduce(methodSelector).Body; if (expr.NodeType == ExpressionType.Call) { @@ -98,13 +93,8 @@ public void ConfigureExport(PropertyInfo propertyInfo, ExportConventionBuilder e _configureExport?.Invoke(exportBuilder); } - private static PropertyInfo SelectProperties(Expression> propertySelector) + private static PropertyInfo SelectProperties(Expression> propertySelector!!) { - if (propertySelector == null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } - Expression expr = Reduce(propertySelector).Body; if (expr.NodeType == ExpressionType.MemberAccess) { @@ -157,13 +147,8 @@ public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConve return; } - private void ParseSelectConstructor(Expression> constructorSelector) + private void ParseSelectConstructor(Expression> constructorSelector!!) { - if (constructorSelector == null) - { - throw new ArgumentNullException(nameof(constructorSelector)); - } - Expression expr = Reduce(constructorSelector).Body; if (expr.NodeType != ExpressionType.New) { @@ -218,13 +203,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(constructorSelector)); - } - var adapter = new ConstructorExpressionAdapter(constructorSelector); base.SelectConstructor(adapter.SelectConstructor, adapter.ConfigureConstructorImports); return this; @@ -247,14 +227,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } - var adapter = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); base.ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); return this; @@ -280,14 +255,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } - var adapter = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration); base.ExportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureExport); return this; @@ -310,14 +280,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } - var adapter = new PropertyExpressionAdapter(propertySelector, importConfiguration, null); base.ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); return this; @@ -342,14 +307,9 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertySelector)); - } - var adapter = new PropertyExpressionAdapter(propertySelector, importConfiguration, null); base.ImportProperties(adapter.VerifyPropertyInfo, adapter.ConfigureImport); return this; @@ -359,13 +319,8 @@ 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 == 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 b8b01750bdef2e..44b0f727656728 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,13 +41,8 @@ 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 == 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 afb9a5b59f6f56..1bec402bf8faf4 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,23 +37,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (site == null) - { - throw new ArgumentNullException(nameof(site)); - } - return new CompositionDependency(contract, target, isPrerequisite, site); } @@ -64,18 +49,8 @@ public static CompositionDependency Satisfied(CompositionContract contract, Expo /// 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 == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (site == null) - { - throw new ArgumentNullException(nameof(site)); - } - return new CompositionDependency(contract, site); } @@ -87,23 +62,8 @@ public static CompositionDependency Missing(CompositionContract contract, object /// 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 == null) - { - throw new ArgumentNullException(nameof(contract)); - } - - if (targets == null) - { - throw new ArgumentNullException(nameof(targets)); - } - - if (site == 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 8feef63077f259..aee870a0d404dd 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,18 +28,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(outermostLifetimeContext)); - } - - if (compositionRootActivator == null) - { - throw new ArgumentNullException(nameof(compositionRootActivator)); - } - using (var operation = new CompositionOperation()) { var result = compositionRootActivator(outermostLifetimeContext, operation); @@ -53,11 +43,8 @@ public static object Run(LifetimeContext outermostLifetimeContext, CompositeActi /// prerequisite part dependencies have been satisfied. /// /// Action to run. - public void AddNonPrerequisiteAction(Action action) + public void AddNonPrerequisiteAction(Action action!!) { - if (action == null) - throw new ArgumentNullException(nameof(action)); - if (_nonPrerequisiteActions == null) _nonPrerequisiteActions = new List(); @@ -69,13 +56,8 @@ 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 == 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 f85aa1be1e1531..0bfcddd06ae001 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,16 +10,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(activator)); - } - if (metadata == 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 d76687440ee469..55fb1829e834ce 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,24 +8,14 @@ namespace System.Composition.Hosting.Util { internal static class Formatters { - public static string ReadableList(IEnumerable items) + public static string ReadableList(IEnumerable items!!) { - if (items == 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 == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (type.IsConstructedGenericType) { return FormatClosedGeneric(type); @@ -33,13 +23,8 @@ public static string Format(Type type) return type.Name; } - private static string FormatClosedGeneric(Type closedGenericType) + private static string FormatClosedGeneric(Type closedGenericType!!) { - if (closedGenericType == 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 dabcc4491b5ad6..7d94fa7fa954db 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 ?? throw new ArgumentNullException(nameof(exportCreator)); + _exportLifetimeContextCreator = 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 c584217d8501e8..68be062b230599 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,10 +138,8 @@ 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 == 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 bf11f260c8a338..6f510121afc879 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,11 +9,8 @@ namespace System.Composition.Runtime.Util { internal static class Formatters { - public static string Format(object value) + public static string Format(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (value is string) return "\"" + value + "\""; 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 54736c2bbc350b..41b6d61b32fb42 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/CompositionContextExtensions.cs @@ -42,12 +42,8 @@ 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 == null) throw new ArgumentNullException(nameof(exportProvider)); - if (objectWithLooseImports == null) throw new ArgumentNullException(nameof(objectWithLooseImports)); - if (conventions == 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 ac6433208b08e4..9c2f37764aab2e 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,9 +47,8 @@ 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 == null) throw new ArgumentNullException(nameof(exportDescriptorProvider)); _addedSources.Add(exportDescriptorProvider); return this; } @@ -61,10 +60,8 @@ public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescri /// /// /// A configuration object allowing configuration to continue. - public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions) + public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions!!) { - if (conventions == null) throw new ArgumentNullException(nameof(conventions)); - if (_defaultAttributeContext != null) throw new InvalidOperationException(SR.ContainerConfiguration_DefaultConventionSet); @@ -148,9 +145,8 @@ 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 == null) throw new ArgumentNullException(nameof(partTypes)); _types.Add(Tuple.Create(partTypes, conventions)); return this; } @@ -196,9 +192,8 @@ 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 == null) throw new ArgumentNullException(nameof(assemblies)); return WithParts(assemblies.SelectMany(a => a.DefinedTypes.Select(dt => dt.AsType())), conventions); } 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 0824f2e318b0be..91e168e04b8212 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,9 +19,8 @@ internal sealed class OnImportsSatisfiedFeature : ActivationFeature { private readonly AttributedModelProvider _attributeContext; - public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext) + public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext!!) { - if (attributeContext == 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 2b54b8c1785a2a..e3afc75a0ea9ee 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,10 +20,9 @@ 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 (reflectedType == null) throw new ArgumentNullException(nameof(reflectedType)); - if (parameter == null) throw new ArgumentNullException(nameof(parameter)); 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 b232f721d46af5..a2657c00f2b164 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs @@ -28,11 +28,8 @@ 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 == null) throw new ArgumentNullException(nameof(key)); - if (type == 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 0e9d0301f1f925..b0f6db13c9cf23 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -55,13 +55,8 @@ 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 == 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 e92c4f215aa63a..0e2d926ef92411 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/CallbackValidator.cs @@ -15,9 +15,8 @@ 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 == 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 7665fc0f569596..9f00b30f51802a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollection.cs @@ -29,10 +29,8 @@ public abstract class ConfigurationElementCollection : ConfigurationElement, ICo protected ConfigurationElementCollection() { } - protected ConfigurationElementCollection(IComparer comparer) + protected ConfigurationElementCollection(IComparer comparer!!) { - if (comparer == 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 cee27df385a207..78449e58857c29 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementProperty.cs @@ -9,10 +9,8 @@ namespace System.Configuration // new overridable on ConfigurationElement public sealed class ConfigurationElementProperty { - public ConfigurationElementProperty(ConfigurationValidatorBase validator) + public ConfigurationElementProperty(ConfigurationValidatorBase validator!!) { - if (validator == 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 e322ba08097d0f..d6cbe437a04253 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionCollection.cs @@ -68,10 +68,8 @@ 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 == 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 7b696a06fb703e..253c360983e0f3 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSectionGroupCollection.cs @@ -65,10 +65,8 @@ 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 == 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 7a6ceb3caf06ba..cd6f9f1aff0e57 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PositiveTimeSpanValidator.cs @@ -10,10 +10,8 @@ public override bool CanValidate(Type type) return type == typeof(TimeSpan); } - public override void Validate(object value) + public override void Validate(object value!!) { - if (value == 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 9023f6be23ed6b..23c4a0e8aaec0d 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertyInformationCollection.cs @@ -39,10 +39,8 @@ 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 == 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 4c111c86800e51..a386057906d0f4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProviderCollection.cs @@ -9,11 +9,8 @@ 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 == 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 23fb407e92fb0f..4f667ff1435543 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsProviderCollection.cs @@ -7,13 +7,8 @@ namespace System.Configuration { public class SettingsProviderCollection : ProviderCollection { - public override void Add(ProviderBase provider) + public override void Add(ProviderBase provider!!) { - if (provider == 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/Resources/Strings.resx b/src/libraries/System.Console/src/Resources/Strings.resx index ce8a2ad62fc9ec..3a814cf13325ff 100644 --- a/src/libraries/System.Console/src/Resources/Strings.resx +++ b/src/libraries/System.Console/src/Resources/Strings.resx @@ -128,9 +128,6 @@ Positive number required. - - Buffer cannot be null. - Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. diff --git a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs index 33ef898edb688c..380257a8af92eb 100644 --- a/src/libraries/System.Console/src/System/IO/SyncTextReader.cs +++ b/src/libraries/System.Console/src/System/IO/SyncTextReader.cs @@ -115,10 +115,8 @@ 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) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) @@ -127,10 +125,8 @@ 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) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 529ff7fcb7a3bf..02a4971b93fd45 100644 --- a/src/libraries/System.Console/src/System/TermInfo.cs +++ b/src/libraries/System.Console/src/System/TermInfo.cs @@ -559,17 +559,8 @@ 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!!) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - if (args == null) - { - throw new ArgumentNullException(nameof(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 f259f711384bea..4d67d37d8edca9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ColumnTypeConverter.cs @@ -68,13 +68,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// [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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 2140301f49ca86..307622604f8ad0 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,12 +52,8 @@ 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!!) { - if (reader is null) - { - throw new ArgumentNullException(nameof(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 664ff2d42b495e..944fdf98ccf34d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintConverter.cs @@ -27,13 +27,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 ac3e4c34f25e7c..62f7cb08d8b92a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataReaderExtensions.cs @@ -3,7 +3,6 @@ using System.ComponentModel; using System.Data.Common; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -12,171 +11,137 @@ 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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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)) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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) { - AssertNotNull(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)) { - AssertNotNull(reader); return reader.IsDBNullAsync(reader.GetOrdinal(name), cancellationToken); } - - private static void AssertNotNull([NotNull] DbDataReader? reader) - { - if (reader is null) - { - throw new ArgumentNullException(nameof(reader)); - } - } } } 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 51985dc6bccee1..db60ac28bf6baa 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DefaultValueTypeConverter.cs @@ -19,13 +19,8 @@ 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 67e643f7cfe521..eda5de868e9603 100644 --- a/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs @@ -19,13 +19,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 c768b3c5e89451..2efdac92ecee1a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs @@ -34,13 +34,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(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 6bcead282f7f36..564cc463ead286 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbException.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbException.cs @@ -35,12 +35,8 @@ 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) { - if (null == si) - { - throw new ArgumentNullException(nameof(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 55cacc67053ea3..e20d26dfd9ad21 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs @@ -94,13 +94,8 @@ 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 9710af30087481..f2bd5299c550ed 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivitySource.cs @@ -18,13 +18,8 @@ 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 = "") { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - Name = name; Version = version; @@ -301,13 +296,8 @@ 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 == 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 55accdb5ed463b..cd45fcb0a2bc0d 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs @@ -34,13 +34,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(list)); - } - foreach (KeyValuePair kvp in list) { if (kvp.Key != null) @@ -142,13 +137,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(key)); - } - int index = FindIndex(key); if (index >= 0) { @@ -219,13 +209,8 @@ 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 == 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 d79c22f995622f..14bc09e190516d 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,18 +37,8 @@ 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) { - if (meter == null) - { - throw new ArgumentNullException(nameof(meter)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - Meter = meter; Name = name; Description = description; 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 b16bbf08835afa..b26f5a200c24cc 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,13 +30,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - Name = name; Version = version; 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 0a77bddd238b1d..730197e106453b 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,35 +20,20 @@ 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) { - if (observeValue is null) - { - throw new ArgumentNullException(nameof(observeValue)); - } - _callback = 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) { - if (observeValue is null) - { - throw new ArgumentNullException(nameof(observeValue)); - } - _callback = 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) { - if (observeValues is null) - { - throw new ArgumentNullException(nameof(observeValues)); - } - _callback = 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 a6e519d564d717..fe2f5d3f10f992 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,35 +20,20 @@ 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) { - if (observeValue is null) - { - throw new ArgumentNullException(nameof(observeValue)); - } - _callback = 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) { - if (observeValue is null) - { - throw new ArgumentNullException(nameof(observeValue)); - } - _callback = 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) { - if (observeValues is null) - { - throw new ArgumentNullException(nameof(observeValues)); - } - _callback = 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 7751067ac55a32..dcd4ff447266b2 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,35 +20,20 @@ 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) { - if (observeValue is null) - { - throw new ArgumentNullException(nameof(observeValue)); - } - _callback = 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) { - if (observeValue is null) - { - throw new ArgumentNullException(nameof(observeValue)); - } - _callback = 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) { - if (observeValues is null) - { - throw new ArgumentNullException(nameof(observeValues)); - } - _callback = 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 ab7f4165b94511..2c576c3c0d8949 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,13 +261,8 @@ 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 6eab2a131f7e4c..3cf5c9e1b1dcfd 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -243,11 +243,8 @@ 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!!) { - if (sourceData == null) - throw new ArgumentNullException(nameof(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 cc4c6198e178cb..3a67a6ead1810c 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -109,11 +109,8 @@ 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) { - //look out for invalid log names - if (logName == null) - throw new ArgumentNullException(nameof(logName)); if (!ValidLogName(logName, true)) throw new ArgumentException(SR.BadLogName); @@ -1314,10 +1311,8 @@ 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) { - if (instance == null) - throw new ArgumentNullException(nameof(instance)); 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 10c499bf082e3d..55e01f5f1149ff 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,9 +17,9 @@ namespace System.Diagnostics.Eventing.Reader /// public class EventBookmark { - internal EventBookmark(string bookmarkText) + internal EventBookmark(string bookmarkText!!) { - BookmarkText = bookmarkText ?? throw new ArgumentNullException(nameof(bookmarkText)); + BookmarkText = bookmarkText; } internal string BookmarkText { get; } 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 02b1f9db81e4f7..ea815291cbf67b 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,11 +13,8 @@ namespace System.Diagnostics.Eventing.Reader /// public class EventLogPropertySelector : IDisposable { - public EventLogPropertySelector(IEnumerable propertyQueries) + public EventLogPropertySelector(IEnumerable propertyQueries!!) { - if (propertyQueries == null) - throw new ArgumentNullException(nameof(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 d42d20e7a0109c..b56215642aa9fb 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,11 +62,8 @@ public EventLogReader(EventLogQuery eventQuery) { } - public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark) + public EventLogReader(EventLogQuery eventQuery!!, EventBookmark bookmark) { - if (eventQuery == null) - throw new ArgumentNullException(nameof(eventQuery)); - string logfile = null; if (eventQuery.ThePathType == PathType.FilePath) logfile = eventQuery.Path; @@ -231,11 +228,8 @@ public void Seek(EventBookmark bookmark) Seek(bookmark, 0); } - public void Seek(EventBookmark bookmark, long offset) + public void Seek(EventBookmark bookmark!!, long offset) { - if (bookmark == null) - throw new ArgumentNullException(nameof(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 bb54bd0ae3faae..136daa04cb9d71 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,10 +389,8 @@ public override IList Properties } } - public IList GetPropertyValues(EventLogPropertySelector propertySelector) + public IList GetPropertyValues(EventLogPropertySelector propertySelector!!) { - if (propertySelector == null) - throw new ArgumentNullException(nameof(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 285359ddd591f7..be9edaa67d88a6 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,11 +203,8 @@ public IEnumerable GetLogNames() } } - public EventLogInformation GetLogInformation(string logName, PathType pathType) + public EventLogInformation GetLogInformation(string logName!!, PathType pathType) { - if (logName == null) - throw new ArgumentNullException(nameof(logName)); - return new EventLogInformation(this, logName, pathType); } @@ -216,13 +213,8 @@ 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) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - - if (targetFilePath == null) - throw new ArgumentNullException(nameof(targetFilePath)); UnsafeNativeMethods.EvtExportLogFlags flag = pathType switch { PathType.LogName => UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogChannelPath, @@ -252,11 +244,8 @@ public void ClearLog(string logName) this.ClearLog(logName, null); } - public void ClearLog(string logName, string backupPath) + public void ClearLog(string logName!!, string backupPath) { - if (logName == null) - throw new ArgumentNullException(nameof(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 1c5a027504fc58..1d2994f0b4ff6e 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,14 +49,8 @@ public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark) { } - public EventLogWatcher(EventLogQuery eventQuery, EventBookmark bookmark, bool readExistingEvents) + public EventLogWatcher(EventLogQuery eventQuery!!, EventBookmark bookmark, bool readExistingEvents) { - - if (eventQuery == null) - { - throw new ArgumentNullException(nameof(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 fe7d96acc34cee..98f40d1df1cba4 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/CounterCreationDataCollection.cs @@ -39,24 +39,16 @@ public int Add(CounterCreationData value) return List.Add(value); } - public void AddRange(CounterCreationData[] value) + public void AddRange(CounterCreationData[] value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(CounterCreationDataCollection value) + public void AddRange(CounterCreationDataCollection value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } int currentCount = value.Count; for (int i = 0; i < currentCount; i++) { @@ -89,11 +81,8 @@ public virtual void Remove(CounterCreationData value) List.Remove(value); } - protected override void OnValidate(object value) + protected override void OnValidate(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(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 a37cb291d4ff2f..1e9d53b49216f2 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs @@ -15,10 +15,8 @@ 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!!) { - if (counterName == null) - throw new ArgumentNullException(nameof(counterName)); CounterName = counterName; } @@ -58,11 +56,8 @@ internal void Add(string instanceName, InstanceData value) Dictionary.Add(objectName, value); } - public bool Contains(string instanceName) + public bool Contains(string instanceName!!) { - if (instanceName == null) - throw new ArgumentNullException(nameof(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 1628c8e9aebe2b..ad556f300c76e4 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs @@ -49,11 +49,8 @@ internal void Add(string counterName, InstanceDataCollection value) Dictionary.Add(objectName, value); } - public bool Contains(string counterName) + public bool Contains(string counterName!!) { - if (counterName == null) - throw new ArgumentNullException(nameof(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 8fd6b54519b7d8..727dce4931188c 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs @@ -41,11 +41,8 @@ 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) { - if (categoryName == null) - throw new ArgumentNullException(nameof(categoryName)); - if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); @@ -150,11 +147,8 @@ public string MachineName /// /// Returns true if the counter is registered for this category /// - public bool CounterExists(string counterName) + public bool CounterExists(string counterName!!) { - if (counterName == null) - throw new ArgumentNullException(nameof(counterName)); - if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); @@ -172,14 +166,8 @@ 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) { - if (counterName == null) - throw new ArgumentNullException(nameof(counterName)); - - if (categoryName == null) - throw new ArgumentNullException(nameof(categoryName)); - if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); @@ -254,11 +242,8 @@ 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!!) { - if (categoryName == null) - throw new ArgumentNullException(nameof(categoryName)); - if (!CheckValidId(categoryName, MaxCategoryNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCategoryName, 1, MaxCategoryNameLength)); @@ -268,11 +253,8 @@ internal static void CheckValidCategory(string categoryName) throw new ArgumentException(SR.CategoryNameTooLong); } - internal static void CheckValidCounter(string counterName) + internal static void CheckValidCounter(string counterName!!) { - if (counterName == null) - throw new ArgumentNullException(nameof(counterName)); - if (!CheckValidId(counterName, MaxCounterNameLength)) throw new ArgumentException(SR.Format(SR.PerfInvalidCounterName, 1, MaxCounterNameLength)); } @@ -300,10 +282,8 @@ internal static bool CheckValidId(string id, int maxLength) return true; } - internal static void CheckValidHelp(string help) + internal static void CheckValidHelp(string help!!) { - if (help == null) - throw new ArgumentNullException(nameof(help)); if (help.Length > MaxHelpLength) throw new ArgumentException(SR.Format(SR.PerfInvalidHelp, 0, MaxHelpLength)); } @@ -421,11 +401,8 @@ 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) { - if (categoryName == null) - throw new ArgumentNullException(nameof(categoryName)); - if (categoryName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName)); @@ -471,11 +448,8 @@ 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!!) { - if (instanceName == null) - throw new ArgumentNullException(nameof(instanceName)); - if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); @@ -529,11 +503,8 @@ public string[] GetInstanceNames() /// /// Returns true if the instance already exists for this category. /// - public bool InstanceExists(string instanceName) + public bool InstanceExists(string instanceName!!) { - if (instanceName == null) - throw new ArgumentNullException(nameof(instanceName)); - if (_categoryName == null) throw new InvalidOperationException(SR.CategoryNameNotSet); @@ -554,14 +525,8 @@ 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) { - if (instanceName == null) - throw new ArgumentNullException(nameof(instanceName)); - - if (categoryName == null) - throw new ArgumentNullException(nameof(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 64ac5f49e0244c..e2e2021d52ed42 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,12 +124,8 @@ 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!!) { - if (counterName == null) - { - throw new ArgumentNullException(nameof(counterName)); - } if (counterName.Length == 0) { throw new ArgumentException(SR.Perflib_Argument_EmptyCounterName, nameof(counterName)); @@ -172,12 +168,8 @@ 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!!) { - if (instanceName == null) - { - throw new ArgumentNullException(nameof(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 cce28bba1a1756..4b5782bd322a65 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,16 +17,8 @@ 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!!) { - if (counterSetDefined == null) - { - throw new ArgumentNullException(nameof(counterSetDefined)); - } - if (instanceName == null) - { - throw new ArgumentNullException(nameof(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 aba0040a1eb84e..7fee3aa86ac151 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,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(counterName)); - } if (counterName.Length == 0) { throw new ArgumentNullException(nameof(counterName)); 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 e75dd7961866f8..2aeee088c509e9 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.cs @@ -568,10 +568,7 @@ public ProcessStartInfo StartInfo } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (Associated) { @@ -1295,13 +1292,8 @@ 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!!) { - if (fileName == null) - throw new ArgumentNullException(nameof(fileName)); - if (arguments == null) - throw new ArgumentNullException(nameof(arguments)); - var startInfo = new ProcessStartInfo(fileName); foreach (string argument in arguments) { @@ -1322,12 +1314,9 @@ 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!!) { Process process = new Process(); - if (startInfo == null) - throw new ArgumentNullException(nameof(startInfo)); - process.StartInfo = startInfo; return process.Start() ? process : 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 28325cc356a9bf..a866d717e02cfc 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/TextWriterTraceListener.cs @@ -38,10 +38,9 @@ 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) { - if (stream == null) throw new ArgumentNullException(nameof(stream)); _writer = new StreamWriter(stream); } @@ -60,10 +59,9 @@ public TextWriterTraceListener(TextWriter writer) /// debugging /// output. /// - public TextWriterTraceListener(TextWriter writer, string? name) + public TextWriterTraceListener(TextWriter writer!!, string? name) : base(name) { - if (writer == null) throw new ArgumentNullException(nameof(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 c5f67fc2139b96..518eb61be51014 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs @@ -27,13 +27,8 @@ internal CorrelationManager() public Guid ActivityId { get { return _activityId.Value; } set { _activityId.Value = value; } } - public void StartLogicalOperation(object operationId) + public void StartLogicalOperation(object operationId!!) { - if (operationId == null) - { - throw new ArgumentNullException(nameof(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 e792cd846b762a..f5275623743fa1 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/SourceFilter.cs @@ -16,12 +16,9 @@ public SourceFilter(string source) Source = source; } - public override bool ShouldTrace(TraceEventCache? cache, string source, TraceEventType eventType, int id, string? formatOrMessage, + public override bool ShouldTrace(TraceEventCache? cache, string source!!, TraceEventType eventType, int id, string? formatOrMessage, object?[]? args, object? data1, object?[]? data) { - if (source == null) - throw new ArgumentNullException(nameof(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 09d2ce791e48a8..a1045d0ab7e7bc 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs @@ -83,12 +83,8 @@ public int Add(TraceListener listener) /// /// [To be supplied.] /// - public void AddRange(TraceListener[] value) + public void AddRange(TraceListener[] value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) { this.Add(value[i]); @@ -98,12 +94,8 @@ public void AddRange(TraceListener[] value) /// /// [To be supplied.] /// - public void AddRange(TraceListenerCollection value) + public void AddRange(TraceListenerCollection value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { @@ -150,11 +142,8 @@ public IEnumerator GetEnumerator() return _list.GetEnumerator(); } - internal void InitializeListener(TraceListener listener) + internal void InitializeListener(TraceListener listener!!) { - if (listener == null) - throw new ArgumentNullException(nameof(listener)); - listener.IndentSize = TraceInternal.IndentSize; listener.IndentLevel = TraceInternal.IndentLevel; } 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 1b91fd7c4de769..a717a45e7bd03a 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,11 +10,8 @@ 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) { - if (format == null) - throw new ArgumentNullException(nameof(format)); - // no need to turn on invalid encoding detection as we just do string->byte[] conversion. UTF8Encoding utf8Encoder = new UTF8Encoding(); byte[] encodingResult = null; @@ -301,11 +298,8 @@ 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) { - if (format == null) - throw new ArgumentNullException(nameof(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 078f298a60fa4e..ea46a1b47ea971 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,26 +33,14 @@ public DirectoryAttribute(string name, Uri value) : this(name, (object)value) { } - internal DirectoryAttribute(string name, object value) : this() + internal DirectoryAttribute(string name!!, object value!!) : this() { - if (name == null) - throw new ArgumentNullException(nameof(name)); - - if (value == null) - throw new ArgumentNullException(nameof(value)); - Name = name; Add(value); } - public DirectoryAttribute(string name, params object[] values) : this() + public DirectoryAttribute(string name!!, params object[] values!!) : this() { - if (name == null) - throw new ArgumentNullException(nameof(name)); - - if (values == null) - throw new ArgumentNullException(nameof(values)); - Name = name; for (int i = 0; i < values.Length; i++) @@ -166,12 +154,8 @@ public object this[int index] public int Add(Uri value) => Add((object)value); - internal int Add(object value) + internal int Add(object value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } if (!(value is string) && !(value is byte[]) && !(value is Uri)) { throw new ArgumentException(SR.ValidValueType, nameof(value)); @@ -180,12 +164,8 @@ internal int Add(object value) return List.Add(value); } - public void AddRange(object[] values) + public void AddRange(object[] values!!) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } if (!(values is string[]) && !(values is byte[][]) && !(values is Uri[])) { throw new ArgumentException(SR.ValidValuesType, nameof(values)); @@ -214,24 +194,15 @@ 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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } if (!(value is string) && !(value is byte[]) && !(value is Uri)) { throw new ArgumentException(SR.ValidValueType, nameof(value)); @@ -289,13 +260,8 @@ internal void Add(string name, DirectoryAttribute value) Dictionary.Add(name.ToLowerInvariant(), value); } - public bool Contains(string attributeName) + public bool Contains(string attributeName!!) { - if (attributeName == null) - { - throw new ArgumentNullException(nameof(attributeName)); - } - object objectName = attributeName.ToLowerInvariant(); return Dictionary.Contains(objectName); } @@ -325,13 +291,8 @@ public int Add(DirectoryAttribute attribute) return List.Add(attribute); } - public void AddRange(DirectoryAttribute[] attributes) + public void AddRange(DirectoryAttribute[] attributes!!) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } - foreach (DirectoryAttribute attribute in attributes) { if (attribute == null) @@ -343,13 +304,8 @@ public void AddRange(DirectoryAttribute[] attributes) InnerList.AddRange(attributes); } - public void AddRange(DirectoryAttributeCollection attributeCollection) + public void AddRange(DirectoryAttributeCollection attributeCollection!!) { - if (attributeCollection == null) - { - throw new ArgumentNullException(nameof(attributeCollection)); - } - int currentCount = attributeCollection.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { @@ -410,13 +366,8 @@ public int Add(DirectoryAttributeModification attribute) return List.Add(attribute); } - public void AddRange(DirectoryAttributeModification[] attributes) + public void AddRange(DirectoryAttributeModification[] attributes!!) { - if (attributes == null) - { - throw new ArgumentNullException(nameof(attributes)); - } - foreach (DirectoryAttributeModification attribute in attributes) { if (attribute == null) @@ -428,13 +379,8 @@ public void AddRange(DirectoryAttributeModification[] attributes) InnerList.AddRange(attributes); } - public void AddRange(DirectoryAttributeModificationCollection attributeCollection) + public void AddRange(DirectoryAttributeModificationCollection attributeCollection!!) { - if (attributeCollection == null) - { - throw new ArgumentNullException(nameof(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 c34f9a4e7cc5a6..bdef26646fedb6 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,9 +91,9 @@ 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) { - Type = type ?? throw new ArgumentNullException(nameof(type)); + Type = type; if (value != null) { @@ -408,9 +408,9 @@ 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() { - _serverName = serverName ?? throw new ArgumentNullException(nameof(serverName)); + _serverName = serverName; } public VerifyNameControl(string serverName, int flag) : this(serverName) @@ -635,13 +635,8 @@ 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) { - if (sortKeys == null) - { - throw new ArgumentNullException(nameof(sortKeys)); - } - for (int i = 0; i < sortKeys.Length; i++) { if (sortKeys[i] == null) @@ -1052,23 +1047,13 @@ public DirectoryControl this[int index] set => List[index] = value ?? throw new ArgumentNullException(nameof(value)); } - public int Add(DirectoryControl control) + public int Add(DirectoryControl control!!) { - if (control == null) - { - throw new ArgumentNullException(nameof(control)); - } - return List.Add(control); } - public void AddRange(DirectoryControl[] controls) + public void AddRange(DirectoryControl[] controls!!) { - if (controls == null) - { - throw new ArgumentNullException(nameof(controls)); - } - foreach (DirectoryControl control in controls) { if (control == null) @@ -1080,13 +1065,8 @@ public void AddRange(DirectoryControl[] controls) InnerList.AddRange(controls); } - public void AddRange(DirectoryControlCollection controlCollection) + public void AddRange(DirectoryControlCollection controlCollection!!) { - if (controlCollection == null) - { - throw new ArgumentNullException(nameof(controlCollection)); - } - int currentCount = controlCollection.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { @@ -1100,24 +1080,15 @@ 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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 347fc652187de6..09891e43a74423 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,13 +50,8 @@ public AddRequest(string distinguishedName, params DirectoryAttribute[] attribut } } - public AddRequest(string distinguishedName, string objectClass) : this() + public AddRequest(string distinguishedName, string objectClass!!) : this() { - if (objectClass == null) - { - throw new ArgumentNullException(nameof(objectClass)); - } - DistinguishedName = distinguishedName; var objClassAttr = new DirectoryAttribute() @@ -82,13 +77,8 @@ 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() { - if (attributeName == null) - { - throw new ArgumentNullException(nameof(attributeName)); - } - DistinguishedName = distinguishedName; var mod = new DirectoryAttributeModification() { @@ -130,12 +120,8 @@ public CompareRequest(string distinguishedName, string attributeName, Uri value) CompareRequestHelper(distinguishedName, attributeName, value); } - public CompareRequest(string distinguishedName, DirectoryAttribute assertion) + public CompareRequest(string distinguishedName, DirectoryAttribute assertion!!) { - if (assertion == null) - { - throw new ArgumentNullException(nameof(assertion)); - } if (assertion.Count != 1) { throw new ArgumentException(SR.WrongNumValuesCompare); @@ -144,17 +130,8 @@ 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!!) { - if (attributeName == null) - { - throw new ArgumentNullException(nameof(attributeName)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(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 800f61ec68d493..b9f850d13db467 100644 --- a/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs +++ b/src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs @@ -34,9 +34,9 @@ public class EnumVariant private object _currentValue = s_noMoreValues; private readonly IEnumVariant _enumerator; - public EnumVariant(IEnumVariant en) + public EnumVariant(IEnumVariant en!!) { - _enumerator = en ?? throw new ArgumentNullException(nameof(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 0a6f32845e4a25..0d83c977793497 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs @@ -25,11 +25,8 @@ internal ActiveDirectoryInterSiteTransport(DirectoryContext context, ActiveDirec _cachedEntry = entry; } - public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context, ActiveDirectoryTransportType transport) + public static ActiveDirectoryInterSiteTransport FindByTransportType(DirectoryContext context!!, ActiveDirectoryTransportType transport) { - if (context == null) - throw new ArgumentNullException(nameof(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 f73a65ae2f2d59..3cec6f767e647a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs @@ -55,11 +55,8 @@ public ActiveDirectorySchedule() #pragma warning restore 612, 618 } - public ActiveDirectorySchedule(ActiveDirectorySchedule schedule) : this() + public ActiveDirectorySchedule(ActiveDirectorySchedule schedule!!) : this() { - if (schedule == null) - throw new ArgumentNullException(nameof(schedule)); - bool[] tmpSchedule = schedule._scheduleArray; for (int i = 0; i < 672; i++) _scheduleArray[i] = tmpSchedule[i]; @@ -124,11 +121,8 @@ 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) { - if (days == null) - throw new ArgumentNullException(nameof(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 73a386b9732b95..fcea89f347cc17 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs @@ -84,13 +84,8 @@ protected override void Dispose(bool disposing) #endregion IDisposable #region public methods - public static ActiveDirectorySchema GetSchema(DirectoryContext context) + public static ActiveDirectorySchema GetSchema(DirectoryContext context!!) { - if (context == null) - { - throw new ArgumentNullException(nameof(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 ab0cf6c41c59a5..7e068ce0718d92 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -46,13 +46,8 @@ public class ActiveDirectorySchemaClass : IDisposable private bool _defaultSDSddlFormInitialized; #region constructors - public ActiveDirectorySchemaClass(DirectoryContext context, string ldapDisplayName) + public ActiveDirectorySchemaClass(DirectoryContext context!!, string ldapDisplayName) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); @@ -224,15 +219,9 @@ 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) { ActiveDirectorySchemaClass? schemaClass = null; - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); 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 bef900f6071c2f..fd49fb2a08e1d2 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -77,13 +77,8 @@ public ActiveDirectorySchemaClass this[int index] } } - public int Add(ActiveDirectorySchemaClass schemaClass) + public int Add(ActiveDirectorySchemaClass schemaClass!!) { - if (schemaClass == null) - { - throw new ArgumentNullException(nameof(schemaClass)); - } - if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -99,13 +94,8 @@ public int Add(ActiveDirectorySchemaClass schemaClass) } } - public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) + public void AddRange(ActiveDirectorySchemaClass[] schemaClasses!!) { - if (schemaClasses == null) - { - throw new ArgumentNullException(nameof(schemaClasses)); - } - foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { if (schemaClass == null) @@ -120,13 +110,8 @@ public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) } } - public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) + public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses!!) { - if (schemaClasses == null) - { - throw new ArgumentNullException(nameof(schemaClasses)); - } - foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { if (schemaClass == null) @@ -142,13 +127,8 @@ public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) } } - public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) + public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses!!) { - if (schemaClasses == null) - { - throw new ArgumentNullException(nameof(schemaClasses)); - } - foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses) { if (schemaClass == null) @@ -164,13 +144,8 @@ public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) } } - public void Remove(ActiveDirectorySchemaClass schemaClass) + public void Remove(ActiveDirectorySchemaClass schemaClass!!) { - if (schemaClass == null) - { - throw new ArgumentNullException(nameof(schemaClass)); - } - if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -188,13 +163,8 @@ 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!!) { - if (schemaClass == null) - { - throw new ArgumentNullException(nameof(schemaClass)); - } - if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -210,13 +180,8 @@ public void Insert(int index, ActiveDirectorySchemaClass schemaClass) } } - public bool Contains(ActiveDirectorySchemaClass schemaClass) + public bool Contains(ActiveDirectorySchemaClass schemaClass!!) { - if (schemaClass == null) - { - throw new ArgumentNullException(nameof(schemaClass)); - } - if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -239,13 +204,8 @@ public void CopyTo(ActiveDirectorySchemaClass[] schemaClasses, int index) List.CopyTo(schemaClasses, index); } - public int IndexOf(ActiveDirectorySchemaClass schemaClass) + public int IndexOf(ActiveDirectorySchemaClass schemaClass!!) { - if (schemaClass == null) - { - throw new ArgumentNullException(nameof(schemaClass)); - } - if (!schemaClass.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaClass.Name)); @@ -356,13 +316,8 @@ protected override void OnSetComplete(int index, object oldValue, object newValu } } - protected override void OnValidate(object value) + protected override void OnValidate(object value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 181a6161757c9b..8733223967c17b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs @@ -100,13 +100,8 @@ 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) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); @@ -278,15 +273,9 @@ 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) { ActiveDirectorySchemaProperty? schemaProperty = null; - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); 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 a07d77d39a72a7..ae86871b689622 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -75,13 +75,8 @@ public ActiveDirectorySchemaProperty this[int index] } } - public int Add(ActiveDirectorySchemaProperty schemaProperty) + public int Add(ActiveDirectorySchemaProperty schemaProperty!!) { - if (schemaProperty == null) - { - throw new ArgumentNullException(nameof(schemaProperty)); - } - if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -97,13 +92,8 @@ public int Add(ActiveDirectorySchemaProperty schemaProperty) } } - public void AddRange(ActiveDirectorySchemaProperty[] properties) + public void AddRange(ActiveDirectorySchemaProperty[] properties!!) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } - foreach (ActiveDirectorySchemaProperty property in properties) { if (property == null) @@ -118,13 +108,8 @@ public void AddRange(ActiveDirectorySchemaProperty[] properties) } } - public void AddRange(ActiveDirectorySchemaPropertyCollection properties) + public void AddRange(ActiveDirectorySchemaPropertyCollection properties!!) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } - foreach (ActiveDirectorySchemaProperty property in properties) { if (property == null) @@ -141,13 +126,8 @@ public void AddRange(ActiveDirectorySchemaPropertyCollection properties) } } - public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) + public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties!!) { - if (properties == null) - { - throw new ArgumentNullException(nameof(properties)); - } - foreach (ActiveDirectorySchemaProperty property in properties) { if (property == null) @@ -164,13 +144,8 @@ public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) } } - public void Remove(ActiveDirectorySchemaProperty schemaProperty) + public void Remove(ActiveDirectorySchemaProperty schemaProperty!!) { - if (schemaProperty == null) - { - throw new ArgumentNullException(nameof(schemaProperty)); - } - if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -188,13 +163,8 @@ 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!!) { - if (schemaProperty == null) - { - throw new ArgumentNullException(nameof(schemaProperty)); - } - if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -210,13 +180,8 @@ public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty) } } - public bool Contains(ActiveDirectorySchemaProperty schemaProperty) + public bool Contains(ActiveDirectorySchemaProperty schemaProperty!!) { - if (schemaProperty == null) - { - throw new ArgumentNullException(nameof(schemaProperty)); - } - if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -253,13 +218,8 @@ public void CopyTo(ActiveDirectorySchemaProperty[] properties, int index) List.CopyTo(properties, index); } - public int IndexOf(ActiveDirectorySchemaProperty schemaProperty) + public int IndexOf(ActiveDirectorySchemaProperty schemaProperty!!) { - if (schemaProperty == null) - { - throw new ArgumentNullException(nameof(schemaProperty)); - } - if (!schemaProperty.isBound) { throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, schemaProperty.Name)); @@ -370,10 +330,8 @@ protected override void OnSetComplete(int index, object oldValue, object newValu } } - protected override void OnValidate(object value) + protected override void OnValidate(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(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 1307a7ea7b8736..21cf53e4db79e6 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs @@ -1102,12 +1102,8 @@ protected virtual void Dispose(bool disposing) _disposed = true; } - private static void ValidateArgument(DirectoryContext context, string siteName) + private static void ValidateArgument(DirectoryContext context!!, string siteName) { - // basic validation first - if (context == null) - throw new ArgumentNullException(nameof(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 9c428eaae46ba9..5ea1d759b66944 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs @@ -40,11 +40,8 @@ public ActiveDirectorySite this[int index] } } - public int Add(ActiveDirectorySite site) + public int Add(ActiveDirectorySite site!!) { - if (site == null) - throw new ArgumentNullException(nameof(site)); - if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -54,30 +51,21 @@ 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!!) { - if (sites == null) - throw new ArgumentNullException(nameof(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!!) { - if (sites == null) - throw new ArgumentNullException(nameof(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!!) { - if (site == null) - throw new ArgumentNullException(nameof(site)); - if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -101,11 +89,8 @@ public void CopyTo(ActiveDirectorySite[] array, int index) List.CopyTo(array, index); } - public int IndexOf(ActiveDirectorySite site) + public int IndexOf(ActiveDirectorySite site!!) { - if (site == null) - throw new ArgumentNullException(nameof(site)); - if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -124,11 +109,8 @@ public int IndexOf(ActiveDirectorySite site) return -1; } - public void Insert(int index, ActiveDirectorySite site) + public void Insert(int index, ActiveDirectorySite site!!) { - if (site == null) - throw new ArgumentNullException(nameof(site)); - if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -138,11 +120,8 @@ 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!!) { - if (site == null) - throw new ArgumentNullException(nameof(site)); - if (!site.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, site.Name)); @@ -232,10 +211,8 @@ protected override void OnSetComplete(int index, object oldValue, object newValu } } - protected override void OnValidate(object value) + protected override void OnValidate(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (!(value is ActiveDirectorySite)) throw new ArgumentException(null, nameof(value)); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs index 84f959f94c2812..7670ac88d0227b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs @@ -9,13 +9,8 @@ namespace System.Drawing { public sealed partial class Bitmap { - public unsafe Bitmap(Stream stream, bool useIcm) + public unsafe Bitmap(Stream stream!!, bool useIcm) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - using DrawingCom.IStreamWrapper streamWrapper = DrawingCom.GetComWrapper(new GPStream(stream)); IntPtr bitmap = IntPtr.Zero; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs index 581219b060261b..60a18794093eca 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs @@ -57,17 +57,8 @@ public Bitmap(Type type, string resource) : this(GetResourceStream(type, resourc { } - private static Stream GetResourceStream(Type type, string resource) + private static Stream GetResourceStream(Type type!!, string resource!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (resource == null) - { - throw new ArgumentNullException(nameof(resource)); - } - Stream? stream = type.Module.Assembly.GetManifestResourceStream(type, resource); if (stream == null) { @@ -81,13 +72,8 @@ public Bitmap(int width, int height) : this(width, height, PixelFormat.Format32b { } - public Bitmap(int width, int height, Graphics g) + public Bitmap(int width, int height, Graphics g!!) { - if (g == null) - { - throw new ArgumentNullException(nameof(g)); - } - IntPtr bitmap; int status = Gdip.GdipCreateBitmapFromGraphics(width, height, new HandleRef(g, g.NativeGraphics), out bitmap); Gdip.CheckStatus(status); @@ -121,11 +107,8 @@ public Bitmap(Image original, Size newSize) : this(original, newSize.Width, newS { } - public Bitmap(Image original, int width, int height) : this(width, height, PixelFormat.Format32bppArgb) + public Bitmap(Image original!!, int width, int height) : this(width, height, PixelFormat.Format32bppArgb) { - if (original == null) - throw new ArgumentNullException(nameof(original)); - using (Graphics g = Graphics.FromImage(this)) { g.Clear(Color.Transparent); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs index 42f91976b70b5b..f644b3d2a9a4a7 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs @@ -74,10 +74,8 @@ public GraphicsPath(PointF[] pts, byte[] types) { } - public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode) + public GraphicsPath(Point[] pts!!, byte[] types, FillMode fillMode) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); if (pts.Length != types.Length) throw new ArgumentException(SR.NumberOfPointsAndTypesMustBeSame); @@ -85,10 +83,8 @@ public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode) Gdip.CheckStatus(status); } - public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode) + public GraphicsPath(PointF[] pts!!, byte[] types, FillMode fillMode) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); if (pts.Length != types.Length) throw new ArgumentException(SR.NumberOfPointsAndTypesMustBeSame); @@ -299,18 +295,14 @@ public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3 // // AddBeziers // - public void AddBeziers(params Point[] points) + public void AddBeziers(params Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); int status = Gdip.GdipAddPathBeziersI(_nativePath, points, points.Length); Gdip.CheckStatus(status); } - public void AddBeziers(PointF[] points) + public void AddBeziers(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); int status = Gdip.GdipAddPathBeziers(_nativePath, points, points.Length); Gdip.CheckStatus(status); } @@ -377,10 +369,8 @@ public void AddLine(float x1, float y1, float x2, float y2) // // AddLines // - public void AddLines(Point[] points) + public void AddLines(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (points.Length == 0) throw new ArgumentException(null, nameof(points)); @@ -388,10 +378,8 @@ public void AddLines(Point[] points) Gdip.CheckStatus(status); } - public void AddLines(PointF[] points) + public void AddLines(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (points.Length == 0) throw new ArgumentException(null, nameof(points)); @@ -424,20 +412,14 @@ public void AddPie(float x, float y, float width, float height, float startAngle // // AddPolygon // - public void AddPolygon(Point[] points) + public void AddPolygon(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathPolygonI(_nativePath, points, points.Length); Gdip.CheckStatus(status); } - public void AddPolygon(PointF[] points) + public void AddPolygon(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathPolygon(_nativePath, points, points.Length); Gdip.CheckStatus(status); } @@ -460,10 +442,8 @@ public void AddRectangle(RectangleF rect) // // AddRectangles // - public void AddRectangles(Rectangle[] rects) + public void AddRectangles(Rectangle[] rects!!) { - if (rects == null) - throw new ArgumentNullException(nameof(rects)); if (rects.Length == 0) throw new ArgumentException(null, nameof(rects)); @@ -471,10 +451,8 @@ public void AddRectangles(Rectangle[] rects) Gdip.CheckStatus(status); } - public void AddRectangles(RectangleF[] rects) + public void AddRectangles(RectangleF[] rects!!) { - if (rects == null) - throw new ArgumentNullException(nameof(rects)); if (rects.Length == 0) throw new ArgumentException(null, nameof(rects)); @@ -485,11 +463,8 @@ public void AddRectangles(RectangleF[] rects) // // AddPath // - public void AddPath(GraphicsPath addingPath, bool connect) + public void AddPath(GraphicsPath addingPath!!, bool connect) { - if (addingPath == null) - throw new ArgumentNullException(nameof(addingPath)); - int status = Gdip.GdipAddPathPath(_nativePath, addingPath._nativePath, connect); Gdip.CheckStatus(status); } @@ -506,38 +481,26 @@ public PointF GetLastPoint() // // AddClosedCurve // - public void AddClosedCurve(Point[] points) + public void AddClosedCurve(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathClosedCurveI(_nativePath, points, points.Length); Gdip.CheckStatus(status); } - public void AddClosedCurve(PointF[] points) + public void AddClosedCurve(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathClosedCurve(_nativePath, points, points.Length); Gdip.CheckStatus(status); } - public void AddClosedCurve(Point[] points, float tension) + public void AddClosedCurve(Point[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathClosedCurve2I(_nativePath, points, points.Length, tension); Gdip.CheckStatus(status); } - public void AddClosedCurve(PointF[] points, float tension) + public void AddClosedCurve(PointF[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathClosedCurve2(_nativePath, points, points.Length, tension); Gdip.CheckStatus(status); } @@ -545,58 +508,40 @@ public void AddClosedCurve(PointF[] points, float tension) // // AddCurve // - public void AddCurve(Point[] points) + public void AddCurve(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathCurveI(_nativePath, points, points.Length); Gdip.CheckStatus(status); } - public void AddCurve(PointF[] points) + public void AddCurve(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathCurve(_nativePath, points, points.Length); Gdip.CheckStatus(status); } - public void AddCurve(Point[] points, float tension) + public void AddCurve(Point[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathCurve2I(_nativePath, points, points.Length, tension); Gdip.CheckStatus(status); } - public void AddCurve(PointF[] points, float tension) + public void AddCurve(PointF[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathCurve2(_nativePath, points, points.Length, tension); Gdip.CheckStatus(status); } - public void AddCurve(Point[] points, int offset, int numberOfSegments, float tension) + public void AddCurve(Point[] points!!, int offset, int numberOfSegments, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathCurve3I(_nativePath, points, points.Length, offset, numberOfSegments, tension); Gdip.CheckStatus(status); } - public void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension) + public void AddCurve(PointF[] points!!, int offset, int numberOfSegments, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - int status = Gdip.GdipAddPathCurve3(_nativePath, points, points.Length, offset, numberOfSegments, tension); @@ -615,11 +560,8 @@ public void Reverse() Gdip.CheckStatus(status); } - public void Transform(Matrix matrix) + public void Transform(Matrix matrix!!) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); - int status = Gdip.GdipTransformPath(_nativePath, matrix.NativeMatrix); Gdip.CheckStatus(status); } @@ -640,22 +582,16 @@ public void AddString(string s, FontFamily family, int style, float emSize, Poin AddString(s, family, style, emSize, layout, format); } - public void AddString(string s, FontFamily family, int style, float emSize, Rectangle layoutRect, StringFormat? format) + public void AddString(string s, FontFamily family!!, int style, float emSize, Rectangle layoutRect, StringFormat? format) { - if (family == null) - throw new ArgumentNullException(nameof(family)); - IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat; // note: the NullReferenceException on s.Length is the expected (MS) exception int status = Gdip.GdipAddPathStringI(_nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat); Gdip.CheckStatus(status); } - public void AddString(string s, FontFamily family, int style, float emSize, RectangleF layoutRect, StringFormat? format) + public void AddString(string s, FontFamily family!!, int style, float emSize, RectangleF layoutRect, StringFormat? format) { - if (family == null) - throw new ArgumentNullException(nameof(family)); - IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat; // note: the NullReferenceException on s.Length is the expected (MS) exception int status = Gdip.GdipAddPathString(_nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat); @@ -754,11 +690,8 @@ public bool IsOutlineVisible(PointF pt, Pen pen, Graphics? graphics) return IsOutlineVisible(pt.X, pt.Y, pen, graphics); } - public bool IsOutlineVisible(int x, int y, Pen pen, Graphics? graphics) + public bool IsOutlineVisible(int x, int y, Pen pen!!, Graphics? graphics) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - bool result; IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics; @@ -768,11 +701,8 @@ public bool IsOutlineVisible(int x, int y, Pen pen, Graphics? graphics) return result; } - public bool IsOutlineVisible(float x, float y, Pen pen, Graphics? graphics) + public bool IsOutlineVisible(float x, float y, Pen pen!!, Graphics? graphics) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - bool result; IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics; @@ -867,11 +797,8 @@ public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix? matrix, WarpMo Warp(destPoints, srcRect, matrix, warpMode, FlatnessDefault); } - public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix? matrix, WarpMode warpMode, float flatness) + public void Warp(PointF[] destPoints!!, RectangleF srcRect, Matrix? matrix, WarpMode warpMode, float flatness) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix; int s = Gdip.GdipWarpPath(_nativePath, m, destPoints, destPoints.Length, @@ -890,10 +817,8 @@ public void Widen(Pen pen, Matrix? matrix) Widen(pen, matrix, FlatnessDefault); } - public void Widen(Pen pen, Matrix? matrix, float flatness) + public void Widen(Pen pen!!, Matrix? matrix, float flatness) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); if (PointCount == 0) return; IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs index f0a1bd9aec3b45..aeafa81d13e6bf 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs @@ -26,10 +26,8 @@ public GraphicsPath(FillMode fillMode) public GraphicsPath(PointF[] pts, byte[] types) : this(pts, types, FillMode.Alternate) { } - public unsafe GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode) + public unsafe GraphicsPath(PointF[] pts!!, byte[] types, FillMode fillMode) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); if (pts.Length != types.Length) throw Gdip.StatusException(Gdip.InvalidParameter); @@ -45,10 +43,8 @@ public unsafe GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode) public GraphicsPath(Point[] pts, byte[] types) : this(pts, types, FillMode.Alternate) { } - public unsafe GraphicsPath(Point[] pts, byte[] types, FillMode fillMode) + public unsafe GraphicsPath(Point[] pts!!, byte[] types, FillMode fillMode) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); if (pts.Length != types.Length) throw Gdip.StatusException(Gdip.InvalidParameter); @@ -246,11 +242,8 @@ public bool IsOutlineVisible(float x, float y, Pen pen, Graphics? graphics) return IsOutlineVisible(new PointF(x, y), pen, graphics); } - public bool IsOutlineVisible(PointF pt, Pen pen, Graphics? graphics) + public bool IsOutlineVisible(PointF pt, Pen pen!!, Graphics? graphics) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - Gdip.CheckStatus(Gdip.GdipIsOutlineVisiblePathPoint( new HandleRef(this, _nativePath), pt.X, pt.Y, @@ -267,11 +260,8 @@ public bool IsOutlineVisible(PointF pt, Pen pen, Graphics? graphics) public bool IsOutlineVisible(int x, int y, Pen pen, Graphics? graphics) => IsOutlineVisible(new Point(x, y), pen, graphics); - public bool IsOutlineVisible(Point pt, Pen pen, Graphics? graphics) + public bool IsOutlineVisible(Point pt, Pen pen!!, Graphics? graphics) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - Gdip.CheckStatus(Gdip.GdipIsOutlineVisiblePathPointI( new HandleRef(this, _nativePath), pt.X, pt.Y, @@ -289,10 +279,8 @@ public void AddLine(float x1, float y1, float x2, float y2) Gdip.CheckStatus(Gdip.GdipAddPathLine(new HandleRef(this, _nativePath), x1, y1, x2, y2)); } - public unsafe void AddLines(PointF[] points) + public unsafe void AddLines(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (points.Length == 0) throw new ArgumentException(null, nameof(points)); @@ -309,10 +297,8 @@ public void AddLine(int x1, int y1, int x2, int y2) Gdip.CheckStatus(Gdip.GdipAddPathLineI(new HandleRef(this, _nativePath), x1, y1, x2, y2)); } - public unsafe void AddLines(Point[] points) + public unsafe void AddLines(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (points.Length == 0) throw new ArgumentException(null, nameof(points)); @@ -362,11 +348,8 @@ public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3 x1, y1, x2, y2, x3, y3, x4, y4)); } - public unsafe void AddBeziers(PointF[] points) + public unsafe void AddBeziers(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathBeziers(new HandleRef(this, _nativePath), p, points.Length)); @@ -385,10 +368,8 @@ public void AddBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, in x1, y1, x2, y2, x3, y3, x4, y4)); } - public unsafe void AddBeziers(params Point[] points) + public unsafe void AddBeziers(params Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (points.Length == 0) return; @@ -401,22 +382,16 @@ public unsafe void AddBeziers(params Point[] points) /// /// Add cardinal splines to the path object /// - public unsafe void AddCurve(PointF[] points) + public unsafe void AddCurve(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - - fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve(new HandleRef(this, _nativePath), p, points.Length)); } } - public unsafe void AddCurve(PointF[] points, float tension) + public unsafe void AddCurve(PointF[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (points.Length == 0) return; @@ -426,11 +401,8 @@ public unsafe void AddCurve(PointF[] points, float tension) } } - public unsafe void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension) + public unsafe void AddCurve(PointF[] points!!, int offset, int numberOfSegments, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve3( @@ -438,22 +410,16 @@ public unsafe void AddCurve(PointF[] points, int offset, int numberOfSegments, f } } - public unsafe void AddCurve(Point[] points) + public unsafe void AddCurve(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurveI(new HandleRef(this, _nativePath), p, points.Length)); } } - public unsafe void AddCurve(Point[] points, float tension) + public unsafe void AddCurve(Point[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve2I( @@ -461,11 +427,8 @@ public unsafe void AddCurve(Point[] points, float tension) } } - public unsafe void AddCurve(Point[] points, int offset, int numberOfSegments, float tension) + public unsafe void AddCurve(Point[] points!!, int offset, int numberOfSegments, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathCurve3I( @@ -473,11 +436,8 @@ public unsafe void AddCurve(Point[] points, int offset, int numberOfSegments, fl } } - public unsafe void AddClosedCurve(PointF[] points) + public unsafe void AddClosedCurve(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurve( @@ -485,33 +445,24 @@ public unsafe void AddClosedCurve(PointF[] points) } } - public unsafe void AddClosedCurve(PointF[] points, float tension) + public unsafe void AddClosedCurve(PointF[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurve2(new HandleRef(this, _nativePath), p, points.Length, tension)); } } - public unsafe void AddClosedCurve(Point[] points) + public unsafe void AddClosedCurve(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurveI(new HandleRef(this, _nativePath), p, points.Length)); } } - public unsafe void AddClosedCurve(Point[] points, float tension) + public unsafe void AddClosedCurve(Point[] points!!, float tension) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathClosedCurve2I(new HandleRef(this, _nativePath), p, points.Length, tension)); @@ -525,10 +476,8 @@ public void AddRectangle(RectangleF rect) rect.X, rect.Y, rect.Width, rect.Height)); } - public unsafe void AddRectangles(RectangleF[] rects) + public unsafe void AddRectangles(RectangleF[] rects!!) { - if (rects == null) - throw new ArgumentNullException(nameof(rects)); if (rects.Length == 0) throw new ArgumentException(null, nameof(rects)); @@ -546,10 +495,8 @@ public void AddRectangle(Rectangle rect) rect.X, rect.Y, rect.Width, rect.Height)); } - public unsafe void AddRectangles(Rectangle[] rects) + public unsafe void AddRectangles(Rectangle[] rects!!) { - if (rects == null) - throw new ArgumentNullException(nameof(rects)); if (rects.Length == 0) throw new ArgumentException(null, nameof(rects)); @@ -600,11 +547,8 @@ public void AddPie(int x, int y, int width, int height, float startAngle, float sweepAngle)); } - public unsafe void AddPolygon(PointF[] points) + public unsafe void AddPolygon(PointF[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathPolygon(new HandleRef(this, _nativePath), p, points.Length)); @@ -614,22 +558,16 @@ public unsafe void AddPolygon(PointF[] points) /// /// Adds a polygon to the current figure. /// - public unsafe void AddPolygon(Point[] points) + public unsafe void AddPolygon(Point[] points!!) { - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { Gdip.CheckStatus(Gdip.GdipAddPathPolygonI(new HandleRef(this, _nativePath), p, points.Length)); } } - public void AddPath(GraphicsPath addingPath, bool connect) + public void AddPath(GraphicsPath addingPath!!, bool connect) { - if (addingPath == null) - throw new ArgumentNullException(nameof(addingPath)); - Gdip.CheckStatus(Gdip.GdipAddPathPath( new HandleRef(this, _nativePath), new HandleRef(addingPath, addingPath._nativePath), connect)); } @@ -644,11 +582,8 @@ public void AddString(string s, FontFamily family, int style, float emSize, Poin AddString(s, family, style, emSize, new Rectangle(origin.X, origin.Y, 0, 0), format); } - public void AddString(string s, FontFamily family, int style, float emSize, RectangleF layoutRect, StringFormat? format) + public void AddString(string s, FontFamily family!!, int style, float emSize, RectangleF layoutRect, StringFormat? format) { - if (family == null) - throw new ArgumentNullException(nameof(family)); - Gdip.CheckStatus(Gdip.GdipAddPathString( new HandleRef(this, _nativePath), s, @@ -660,11 +595,8 @@ public void AddString(string s, FontFamily family, int style, float emSize, Rect new HandleRef(format, format?.nativeFormat ?? IntPtr.Zero))); } - public void AddString(string s, FontFamily family, int style, float emSize, Rectangle layoutRect, StringFormat? format) + public void AddString(string s, FontFamily family!!, int style, float emSize, Rectangle layoutRect, StringFormat? format) { - if (family == null) - throw new ArgumentNullException(nameof(family)); - Gdip.CheckStatus(Gdip.GdipAddPathStringI( new HandleRef(this, _nativePath), s, @@ -676,10 +608,8 @@ public void AddString(string s, FontFamily family, int style, float emSize, Rect new HandleRef(format, format?.nativeFormat ?? IntPtr.Zero))); } - public void Transform(Matrix matrix) + public void Transform(Matrix matrix!!) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); if (matrix.NativeMatrix == IntPtr.Zero) return; @@ -719,11 +649,8 @@ public void Flatten(Matrix? matrix, float flatness) public void Widen(Pen pen, Matrix? matrix) => Widen(pen, matrix, Flatness); - public void Widen(Pen pen, Matrix? matrix, float flatness) + public void Widen(Pen pen!!, Matrix? matrix, float flatness) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - // GDI+ wrongly returns an out of memory status when there is nothing in the path, so we have to check // before calling the widen method and do nothing if we dont have anything in the path. if (PointCount == 0) @@ -745,11 +672,8 @@ public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix? matrix, WarpMo Warp(destPoints, srcRect, matrix, warpMode, 0.25f); } - public unsafe void Warp(PointF[] destPoints, RectangleF srcRect, Matrix? matrix, WarpMode warpMode, float flatness) + public unsafe void Warp(PointF[] destPoints!!, RectangleF srcRect, Matrix? matrix, WarpMode warpMode, float flatness) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - fixed (PointF* p = destPoints) { Gdip.CheckStatus(Gdip.GdipWarpPath( diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs index a01a61e01843e5..56afa27cee56dc 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs @@ -476,11 +476,8 @@ public void ResetTransform() public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); - public void MultiplyTransform(Matrix matrix, MatrixOrder order) + public void MultiplyTransform(Matrix matrix!!, MatrixOrder order) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); - // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws // with the libgdiplus backend. Simulate a nop for compatability with GDI+. if (matrix.NativeMatrix == IntPtr.Zero) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs index a0ed155d9767a0..d418b7a7d30554 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs @@ -52,10 +52,8 @@ internal static IntPtr CreateNativeHandle(Matrix3x2 matrix) return nativeMatrix; } - public unsafe Matrix(RectangleF rect, PointF[] plgpts) + public unsafe Matrix(RectangleF rect, PointF[] plgpts!!) { - if (plgpts == null) - throw new ArgumentNullException(nameof(plgpts)); if (plgpts.Length != 3) throw Gdip.StatusException(Gdip.InvalidParameter); @@ -66,10 +64,8 @@ public unsafe Matrix(RectangleF rect, PointF[] plgpts) } } - public unsafe Matrix(Rectangle rect, Point[] plgpts) + public unsafe Matrix(Rectangle rect, Point[] plgpts!!) { - if (plgpts == null) - throw new ArgumentNullException(nameof(plgpts)); if (plgpts.Length != 3) throw Gdip.StatusException(Gdip.InvalidParameter); @@ -174,10 +170,8 @@ public void Reset() public void Multiply(Matrix matrix) => Multiply(matrix, MatrixOrder.Prepend); - public void Multiply(Matrix matrix, MatrixOrder order) + public void Multiply(Matrix matrix!!, MatrixOrder order) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); if (matrix.NativeMatrix == NativeMatrix) throw new InvalidOperationException(SR.GdiplusObjectBusy); @@ -246,11 +240,8 @@ public void Invert() Gdip.CheckStatus(Gdip.GdipInvertMatrix(new HandleRef(this, NativeMatrix))); } - public unsafe void TransformPoints(PointF[] pts) + public unsafe void TransformPoints(PointF[] pts!!) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); - fixed (PointF* p = pts) { Gdip.CheckStatus(Gdip.GdipTransformMatrixPoints( @@ -260,11 +251,8 @@ public unsafe void TransformPoints(PointF[] pts) } } - public unsafe void TransformPoints(Point[] pts) + public unsafe void TransformPoints(Point[] pts!!) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); - fixed (Point* p = pts) { Gdip.CheckStatus(Gdip.GdipTransformMatrixPointsI( @@ -274,11 +262,8 @@ public unsafe void TransformPoints(Point[] pts) } } - public unsafe void TransformVectors(PointF[] pts) + public unsafe void TransformVectors(PointF[] pts!!) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); - fixed (PointF* p = pts) { Gdip.CheckStatus(Gdip.GdipVectorTransformMatrixPoints( @@ -290,11 +275,8 @@ public unsafe void TransformVectors(PointF[] pts) public void VectorTransformPoints(Point[] pts) => TransformVectors(pts); - public unsafe void TransformVectors(Point[] pts) + public unsafe void TransformVectors(Point[] pts!!) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); - fixed (Point* p = pts) { Gdip.CheckStatus(Gdip.GdipVectorTransformMatrixPointsI( diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs index cfbef11ee09a13..d05f2585e08f72 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs @@ -13,10 +13,8 @@ public sealed class PathGradientBrush : Brush { public PathGradientBrush(PointF[] points) : this(points, WrapMode.Clamp) { } - public unsafe PathGradientBrush(PointF[] points, WrapMode wrapMode) + public unsafe PathGradientBrush(PointF[] points!!, WrapMode wrapMode) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); @@ -37,10 +35,8 @@ public unsafe PathGradientBrush(PointF[] points, WrapMode wrapMode) public PathGradientBrush(Point[] points) : this(points, WrapMode.Clamp) { } - public unsafe PathGradientBrush(Point[] points, WrapMode wrapMode) + public unsafe PathGradientBrush(Point[] points!!, WrapMode wrapMode) { - if (points == null) - throw new ArgumentNullException(nameof(points)); if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); @@ -59,11 +55,8 @@ public unsafe PathGradientBrush(Point[] points, WrapMode wrapMode) } } - public PathGradientBrush(GraphicsPath path) + public PathGradientBrush(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCreatePathGradientFromPath(new HandleRef(path, path._nativePath), out IntPtr nativeBrush)); SetNativeBrushInternal(nativeBrush); } @@ -338,10 +331,8 @@ public void ResetTransform() public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); - public void MultiplyTransform(Matrix matrix, MatrixOrder order) + public void MultiplyTransform(Matrix matrix!!, MatrixOrder order) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws // with the libgdiplus backend. Simulate a nop for compatability with GDI+. diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs index 9721c7ff5681f7..c30f21eeb4bcb7 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs @@ -262,12 +262,9 @@ public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, { } - public Font(FontFamily family, float emSize, FontStyle style, + public Font(FontFamily family!!, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { - if (family == null) - throw new ArgumentNullException(nameof(family)); - int status; Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont); status = Gdip.GdipCreateFont(new HandleRef(this, family.NativeFamily), emSize, style, unit, out _nativeFont); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs index 46bca48be4c06c..a932a9c17543f4 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs @@ -185,13 +185,8 @@ private void Initialize(string familyName, float emSize, FontStyle style, Graphi /// /// Initializes this object's fields. /// - private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) + private void Initialize(FontFamily family!!, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { - if (family == null) - { - throw new ArgumentNullException(nameof(family)); - } - if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize)); @@ -286,13 +281,8 @@ internal static Font FromLogFontInternal(ref Interop.User32.LOGFONT logFont, Int /// A boxed LOGFONT. /// Handle to a device context (HDC). /// The newly created . - public static unsafe Font FromLogFont(object lf, IntPtr hdc) + public static unsafe Font FromLogFont(object lf!!, IntPtr hdc) { - if (lf == null) - { - throw new ArgumentNullException(nameof(lf)); - } - if (lf is Interop.User32.LOGFONT logFont) { // A boxed LOGFONT, just use it to create the font diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs index 0a738e0e3e8649..3968ee5f63a6fe 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs @@ -199,13 +199,8 @@ private void Dispose(bool disposing) /// /// Returns the height of this Font in the specified graphics context. /// - public float GetHeight(Graphics graphics) + public float GetHeight(Graphics graphics!!) { - if (graphics == null) - { - throw new ArgumentNullException(nameof(graphics)); - } - float height; int status = Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out height); Gdip.CheckStatus(status); @@ -266,13 +261,8 @@ public override string ToString() => // This is used by SystemFonts when constructing a system Font objects. internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName; - public unsafe void ToLogFont(object logFont, Graphics graphics) + public unsafe void ToLogFont(object logFont!!, Graphics graphics) { - if (logFont == null) - { - throw new ArgumentNullException(nameof(logFont)); - } - Type type = logFont.GetType(); int nativeSize = sizeof(Interop.User32.LOGFONT); if (Marshal.SizeOf(type) != nativeSize) @@ -297,13 +287,8 @@ public unsafe void ToLogFont(object logFont, Graphics graphics) } } - private unsafe Interop.User32.LOGFONT ToLogFontInternal(Graphics graphics) + private unsafe Interop.User32.LOGFONT ToLogFontInternal(Graphics graphics!!) { - if (graphics == null) - { - throw new ArgumentNullException(nameof(graphics)); - } - Interop.User32.LOGFONT logFont = default; Gdip.CheckStatus(Gdip.GdipGetLogFontW( new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), ref logFont)); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs index 41a39db24d23d6..07673d93d8bcdb 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs @@ -270,13 +270,8 @@ private GraphicsUnit ParseGraphicsUnits(string units) => _ => throw new ArgumentException(SR.Format(SR.InvalidArgumentValueFontConverter, units), nameof(units)), }; - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) { - if (propertyValues == null) - { - throw new ArgumentNullException(nameof(propertyValues)); - } - object? value; byte charSet = 1; float size = 8; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs index bfd28aeeb6e277..666f19a60461c8 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs @@ -226,13 +226,8 @@ private static IntPtr GetGdipGenericSansSerif() /// graphics context. /// [Obsolete("FontFamily.GetFamilies has been deprecated. Use Families instead.")] - public static FontFamily[] GetFamilies(Graphics graphics) + public static FontFamily[] GetFamilies(Graphics graphics!!) { - if (graphics == null) - { - throw new ArgumentNullException(nameof(graphics)); - } - return new InstalledFontCollection().Families; } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs index eb7135c7082139..f38a92fb91178e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs @@ -250,13 +250,8 @@ public void Dispose() GC.SuppressFinalize(this); } - public void DrawBeziers(Pen pen, Point[] points) + public void DrawBeziers(Pen pen!!, Point[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - int length = points.Length; int status; @@ -278,13 +273,8 @@ public void DrawBeziers(Pen pen, Point[] points) } } - public void DrawBeziers(Pen pen, PointF[] points) + public void DrawBeziers(Pen pen!!, PointF[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - int length = points.Length; int status; @@ -306,34 +296,23 @@ public void DrawBeziers(Pen pen, PointF[] points) } } - public void DrawIcon(Icon icon, Rectangle targetRect) + public void DrawIcon(Icon icon!!, Rectangle targetRect) { - if (icon == null) - throw new ArgumentNullException(nameof(icon)); - DrawImage(icon.GetInternalBitmap(), targetRect); } - public void DrawIcon(Icon icon, int x, int y) + public void DrawIcon(Icon icon!!, int x, int y) { - if (icon == null) - throw new ArgumentNullException(nameof(icon)); - DrawImage(icon.GetInternalBitmap(), x, y); } - public void DrawIconUnstretched(Icon icon, Rectangle targetRect) + public void DrawIconUnstretched(Icon icon!!, Rectangle targetRect) { - if (icon == null) - throw new ArgumentNullException(nameof(icon)); - DrawImageUnscaled(icon.GetInternalBitmap(), targetRect); } - public void DrawLine(Pen pen, float x1, float y1, float x2, float y2) + public void DrawLine(Pen pen!!, float x1, float y1, float x2, float y2) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); if (!float.IsNaN(x1) && !float.IsNaN(y1) && !float.IsNaN(x2) && !float.IsNaN(y2)) { @@ -342,10 +321,8 @@ public void DrawLine(Pen pen, float x1, float y1, float x2, float y2) } } - public void EndContainer(GraphicsContainer container) + public void EndContainer(GraphicsContainer container!!) { - if (container == null) - throw new ArgumentNullException(nameof(container)); int status = Gdip.GdipEndContainer(new HandleRef(this, NativeGraphics), container.nativeGraphicsContainer); Gdip.CheckStatus(status); } @@ -410,24 +387,14 @@ public void EnumerateMetafile(Metafile metafile, PointF destPoint, RectangleF sr throw new NotImplementedException(); } - public void FillPath(Brush brush, GraphicsPath path) + public void FillPath(Brush brush!!, GraphicsPath path!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (path == null) - throw new ArgumentNullException(nameof(path)); - int status = Gdip.GdipFillPath(NativeGraphics, brush.NativeBrush, path._nativePath); Gdip.CheckStatus(status); } - public void FillRegion(Brush brush, Region region) + public void FillRegion(Brush brush!!, Region region!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (region == null) - throw new ArgumentNullException(nameof(region)); - int status = (int)Gdip.GdipFillRegion(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), new HandleRef(region, region.NativeRegion)); Gdip.CheckStatus(status); } @@ -494,16 +461,12 @@ public static Graphics FromHwndInternal(IntPtr hwnd) return FromHwnd(hwnd); } - public static Graphics FromImage(Image image) + public static Graphics FromImage(Image image!!) { - IntPtr graphics; - - if (image == null) - throw new ArgumentNullException(nameof(image)); - if ((image.PixelFormat & PixelFormat.Indexed) != 0) throw new ArgumentException(SR.CannotCreateGraphics, nameof(image)); + IntPtr graphics; int status = Gdip.GdipGetImageGraphicsContext(image.nativeImage, out graphics); Gdip.CheckStatus(status); Graphics result = new Graphics(graphics, image); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs index 475e35a176ceac..1aa55c9ab649c8 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs @@ -109,10 +109,8 @@ public static Graphics FromHwndInternal(IntPtr hwnd) /// /// Creates an instance of the class from an existing . /// - public static Graphics FromImage(Image image) + public static Graphics FromImage(Image image!!) { - if (image == null) - throw new ArgumentNullException(nameof(image)); if ((image.PixelFormat & PixelFormat.Indexed) != 0) throw new ArgumentException(SR.GdiplusCannotCreateGraphicsFromIndexedPixelFormat, nameof(image)); @@ -283,24 +281,16 @@ public Color GetNearestColor(Color color) /// /// Draws a line connecting the two specified points. /// - public void DrawLine(Pen pen, float x1, float y1, float x2, float y2) + public void DrawLine(Pen pen!!, float x1, float y1, float x2, float y2) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawLine(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2)); } /// /// Draws a series of cubic Bezier curves from an array of points. /// - public unsafe void DrawBeziers(Pen pen, PointF[] points) + public unsafe void DrawBeziers(Pen pen!!, PointF[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawBeziers( @@ -313,13 +303,8 @@ public unsafe void DrawBeziers(Pen pen, PointF[] points) /// /// Draws a series of cubic Bezier curves from an array of points. /// - public unsafe void DrawBeziers(Pen pen, Point[] points) + public unsafe void DrawBeziers(Pen pen!!, Point[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawBeziersI( @@ -333,13 +318,8 @@ public unsafe void DrawBeziers(Pen pen, Point[] points) /// /// Fills the interior of a path. /// - public void FillPath(Brush brush, GraphicsPath path) + public void FillPath(Brush brush!!, GraphicsPath path!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (path == null) - throw new ArgumentNullException(nameof(path)); - CheckErrorStatus(Gdip.GdipFillPath( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -349,24 +329,16 @@ public void FillPath(Brush brush, GraphicsPath path) /// /// Fills the interior of a . /// - public void FillRegion(Brush brush, Region region) + public void FillRegion(Brush brush!!, Region region!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (region == null) - throw new ArgumentNullException(nameof(region)); - CheckErrorStatus(Gdip.GdipFillRegion( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), new HandleRef(region, region.NativeRegion))); } - public void DrawIcon(Icon icon, int x, int y) + public void DrawIcon(Icon icon!!, int x, int y) { - if (icon == null) - throw new ArgumentNullException(nameof(icon)); - if (_backingImage != null) { // We don't call the icon directly because we want to stay in GDI+ all the time @@ -386,11 +358,8 @@ public void DrawIcon(Icon icon, int x, int y) /// it passes the call to the actual image. This version crops the image to the given /// dimensions and allows the user to specify a rectangle within the image to draw. /// - public void DrawIcon(Icon icon, Rectangle targetRect) + public void DrawIcon(Icon icon!!, Rectangle targetRect) { - if (icon == null) - throw new ArgumentNullException(nameof(icon)); - if (_backingImage != null) { // We don't call the icon directly because we want to stay in GDI+ all the time @@ -410,11 +379,8 @@ public void DrawIcon(Icon icon, Rectangle targetRect) /// it passes the call to the actual image. This version stretches the image to the given /// dimensions and allows the user to specify a rectangle within the image to draw. /// - public void DrawIconUnstretched(Icon icon, Rectangle targetRect) + public void DrawIconUnstretched(Icon icon!!, Rectangle targetRect) { - if (icon == null) - throw new ArgumentNullException(nameof(icon)); - if (_backingImage != null) { DrawImageUnscaled(icon.ToBitmap(), targetRect); @@ -490,13 +456,11 @@ public void EnumerateMetafile( public unsafe void EnumerateMetafile( Metafile metafile, - PointF[] destPoints, + PointF[] destPoints!!, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes? imageAttr) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); if (destPoints.Length != 3) throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram); @@ -514,13 +478,11 @@ public unsafe void EnumerateMetafile( public unsafe void EnumerateMetafile( Metafile metafile, - Point[] destPoints, + Point[] destPoints!!, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes? imageAttr) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); if (destPoints.Length != 3) throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram); @@ -618,15 +580,13 @@ public void EnumerateMetafile( public unsafe void EnumerateMetafile( Metafile metafile, - PointF[] destPoints, + PointF[] destPoints!!, RectangleF srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes? imageAttr) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); if (destPoints.Length != 3) throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram); @@ -646,15 +606,13 @@ public unsafe void EnumerateMetafile( public unsafe void EnumerateMetafile( Metafile metafile, - Point[] destPoints, + Point[] destPoints!!, Rectangle srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes? imageAttr) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); if (destPoints.Length != 3) throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram); @@ -907,11 +865,8 @@ public GraphicsContainer BeginContainer() return new GraphicsContainer(state); } - public void EndContainer(GraphicsContainer container) + public void EndContainer(GraphicsContainer container!!) { - if (container == null) - throw new ArgumentNullException(nameof(container)); - Gdip.CheckStatus(Gdip.GdipEndContainer(new HandleRef(this, NativeGraphics), container.nativeGraphicsContainer)); PopContext(container.nativeGraphicsContainer); } @@ -935,11 +890,8 @@ public GraphicsContainer BeginContainer(Rectangle dstrect, Rectangle srcrect, Gr return new GraphicsContainer(state); } - public void AddMetafileComment(byte[] data) + public void AddMetafileComment(byte[] data!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - Gdip.CheckStatus(Gdip.GdipComment(new HandleRef(this, NativeGraphics), data.Length, data)); } 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 9bb60157e61589..6120f55482902a 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs @@ -410,11 +410,8 @@ public void Flush(FlushIntention intention) public void SetClip(Graphics g) => SetClip(g, CombineMode.Replace); - public void SetClip(Graphics g, CombineMode combineMode) + public void SetClip(Graphics g!!, CombineMode combineMode) { - if (g == null) - throw new ArgumentNullException(nameof(g)); - Gdip.CheckStatus(Gdip.GdipSetClipGraphics( new HandleRef(this, NativeGraphics), new HandleRef(g, g.NativeGraphics), @@ -443,22 +440,16 @@ public void SetClip(RectangleF rect, CombineMode combineMode) public void SetClip(GraphicsPath path) => SetClip(path, CombineMode.Replace); - public void SetClip(GraphicsPath path, CombineMode combineMode) + public void SetClip(GraphicsPath path!!, CombineMode combineMode) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipSetClipPath( new HandleRef(this, NativeGraphics), new HandleRef(path, path._nativePath), combineMode)); } - public void SetClip(Region region, CombineMode combineMode) + public void SetClip(Region region!!, CombineMode combineMode) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipSetClipRegion( new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion), @@ -481,11 +472,8 @@ public void IntersectClip(RectangleF rect) CombineMode.Intersect)); } - public void IntersectClip(Region region) + public void IntersectClip(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipSetClipRegion( new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion), @@ -500,11 +488,8 @@ public void ExcludeClip(Rectangle rect) CombineMode.Exclude)); } - public void ExcludeClip(Region region) + public void ExcludeClip(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipSetClipRegion( new HandleRef(this, NativeGraphics), new HandleRef(region, region.NativeRegion), @@ -596,11 +581,8 @@ public void ResetTransform() /// /// Multiplies the that represents the world transform and . /// - public void MultiplyTransform(Matrix matrix, MatrixOrder order) + public void MultiplyTransform(Matrix matrix!!, MatrixOrder order) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); - // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws // with the libgdiplus backend. Simulate a nop for compatability with GDI+. if (matrix.NativeMatrix == IntPtr.Zero) @@ -634,11 +616,8 @@ public void RotateTransform(float angle, MatrixOrder order) /// /// Draws an arc from the specified ellipse. /// - public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) + public void DrawArc(Pen pen!!, float x, float y, float width, float height, float startAngle, float sweepAngle) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawArc( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -658,11 +637,8 @@ public void DrawArc(Pen pen, RectangleF rect, float startAngle, float sweepAngle /// /// Draws an arc from the specified ellipse. /// - public void DrawArc(Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle) + public void DrawArc(Pen pen!!, int x, int y, int width, int height, int startAngle, int sweepAngle) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawArcI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -682,11 +658,8 @@ public void DrawArc(Pen pen, Rectangle rect, float startAngle, float sweepAngle) /// /// Draws a cubic bezier curve defined by four ordered pairs that represent points. /// - public void DrawBezier(Pen pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) + public void DrawBezier(Pen pen!!, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawBezier( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2, x3, y3, x4, y4)); @@ -729,11 +702,8 @@ public void DrawRectangle(Pen pen, Rectangle rect) /// /// Draws the outline of the specified rectangle. /// - public void DrawRectangle(Pen pen, float x, float y, float width, float height) + public void DrawRectangle(Pen pen!!, float x, float y, float width, float height) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawRectangle( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height)); @@ -742,11 +712,8 @@ public void DrawRectangle(Pen pen, float x, float y, float width, float height) /// /// Draws the outline of the specified rectangle. /// - public void DrawRectangle(Pen pen, int x, int y, int width, int height) + public void DrawRectangle(Pen pen!!, int x, int y, int width, int height) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawRectangleI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height)); @@ -755,13 +722,8 @@ public void DrawRectangle(Pen pen, int x, int y, int width, int height) /// /// Draws the outlines of a series of rectangles. /// - public unsafe void DrawRectangles(Pen pen, RectangleF[] rects) + public unsafe void DrawRectangles(Pen pen!!, RectangleF[] rects!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (rects == null) - throw new ArgumentNullException(nameof(rects)); - fixed (RectangleF* r = rects) { CheckErrorStatus(Gdip.GdipDrawRectangles( @@ -773,13 +735,8 @@ public unsafe void DrawRectangles(Pen pen, RectangleF[] rects) /// /// Draws the outlines of a series of rectangles. /// - public unsafe void DrawRectangles(Pen pen, Rectangle[] rects) + public unsafe void DrawRectangles(Pen pen!!, Rectangle[] rects!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (rects == null) - throw new ArgumentNullException(nameof(rects)); - fixed (Rectangle* r = rects) { CheckErrorStatus(Gdip.GdipDrawRectanglesI( @@ -799,11 +756,8 @@ public void DrawEllipse(Pen pen, RectangleF rect) /// /// Draws the outline of an ellipse defined by a bounding rectangle. /// - public void DrawEllipse(Pen pen, float x, float y, float width, float height) + public void DrawEllipse(Pen pen!!, float x, float y, float width, float height) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawEllipse( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -821,11 +775,8 @@ public void DrawEllipse(Pen pen, Rectangle rect) /// /// Draws the outline of an ellipse defined by a bounding rectangle. /// - public void DrawEllipse(Pen pen, int x, int y, int width, int height) + public void DrawEllipse(Pen pen!!, int x, int y, int width, int height) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawEllipseI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -843,11 +794,8 @@ public void DrawPie(Pen pen, RectangleF rect, float startAngle, float sweepAngle /// /// Draws the outline of a pie section defined by an ellipse and two radial lines. /// - public void DrawPie(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) + public void DrawPie(Pen pen!!, float x, float y, float width, float height, float startAngle, float sweepAngle) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawPie( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -867,11 +815,8 @@ public void DrawPie(Pen pen, Rectangle rect, float startAngle, float sweepAngle) /// /// Draws the outline of a pie section defined by an ellipse and two radial lines. /// - public void DrawPie(Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle) + public void DrawPie(Pen pen!!, int x, int y, int width, int height, int startAngle, int sweepAngle) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawPieI( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -883,13 +828,8 @@ public void DrawPie(Pen pen, int x, int y, int width, int height, int startAngle /// /// Draws the outline of a polygon defined by an array of points. /// - public unsafe void DrawPolygon(Pen pen, PointF[] points) + public unsafe void DrawPolygon(Pen pen!!, PointF[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawPolygon( @@ -901,13 +841,8 @@ public unsafe void DrawPolygon(Pen pen, PointF[] points) /// /// Draws the outline of a polygon defined by an array of points. /// - public unsafe void DrawPolygon(Pen pen, Point[] points) + public unsafe void DrawPolygon(Pen pen!!, Point[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawPolygonI( @@ -919,13 +854,8 @@ public unsafe void DrawPolygon(Pen pen, Point[] points) /// /// Draws the lines and curves defined by a . /// - public void DrawPath(Pen pen, GraphicsPath path) + public void DrawPath(Pen pen!!, GraphicsPath path!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (path == null) - throw new ArgumentNullException(nameof(path)); - CheckErrorStatus(Gdip.GdipDrawPath( new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), @@ -935,13 +865,8 @@ public void DrawPath(Pen pen, GraphicsPath path) /// /// Draws a curve defined by an array of points. /// - public unsafe void DrawCurve(Pen pen, PointF[] points) + public unsafe void DrawCurve(Pen pen!!, PointF[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve( @@ -954,13 +879,8 @@ public unsafe void DrawCurve(Pen pen, PointF[] points) /// /// Draws a curve defined by an array of points. /// - public unsafe void DrawCurve(Pen pen, PointF[] points, float tension) + public unsafe void DrawCurve(Pen pen!!, PointF[] points!!, float tension) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve2( @@ -979,13 +899,8 @@ public void DrawCurve(Pen pen, PointF[] points, int offset, int numberOfSegments /// /// Draws a curve defined by an array of points. /// - public unsafe void DrawCurve(Pen pen, PointF[] points, int offset, int numberOfSegments, float tension) + public unsafe void DrawCurve(Pen pen!!, PointF[] points!!, int offset, int numberOfSegments, float tension) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve3( @@ -1001,13 +916,8 @@ public unsafe void DrawCurve(Pen pen, PointF[] points, int offset, int numberOfS /// /// Draws a curve defined by an array of points. /// - public unsafe void DrawCurve(Pen pen, Point[] points) + public unsafe void DrawCurve(Pen pen!!, Point[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawCurveI( @@ -1020,13 +930,8 @@ public unsafe void DrawCurve(Pen pen, Point[] points) /// /// Draws a curve defined by an array of points. /// - public unsafe void DrawCurve(Pen pen, Point[] points, float tension) + public unsafe void DrawCurve(Pen pen!!, Point[] points!!, float tension) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve2I( @@ -1040,13 +945,8 @@ public unsafe void DrawCurve(Pen pen, Point[] points, float tension) /// /// Draws a curve defined by an array of points. /// - public unsafe void DrawCurve(Pen pen, Point[] points, int offset, int numberOfSegments, float tension) + public unsafe void DrawCurve(Pen pen!!, Point[] points!!, int offset, int numberOfSegments, float tension) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawCurve3I( @@ -1062,13 +962,8 @@ public unsafe void DrawCurve(Pen pen, Point[] points, int offset, int numberOfSe /// /// Draws a closed curve defined by an array of points. /// - public unsafe void DrawClosedCurve(Pen pen, PointF[] points) + public unsafe void DrawClosedCurve(Pen pen!!, PointF[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurve( @@ -1081,13 +976,8 @@ public unsafe void DrawClosedCurve(Pen pen, PointF[] points) /// /// Draws a closed curve defined by an array of points. /// - public unsafe void DrawClosedCurve(Pen pen, PointF[] points, float tension, FillMode fillmode) + public unsafe void DrawClosedCurve(Pen pen!!, PointF[] points!!, float tension, FillMode fillmode) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurve2( @@ -1101,13 +991,8 @@ public unsafe void DrawClosedCurve(Pen pen, PointF[] points, float tension, Fill /// /// Draws a closed curve defined by an array of points. /// - public unsafe void DrawClosedCurve(Pen pen, Point[] points) + public unsafe void DrawClosedCurve(Pen pen!!, Point[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurveI( @@ -1120,13 +1005,8 @@ public unsafe void DrawClosedCurve(Pen pen, Point[] points) /// /// Draws a closed curve defined by an array of points. /// - public unsafe void DrawClosedCurve(Pen pen, Point[] points, float tension, FillMode fillmode) + public unsafe void DrawClosedCurve(Pen pen!!, Point[] points!!, float tension, FillMode fillmode) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawClosedCurve2I( @@ -1156,11 +1036,8 @@ public void FillRectangle(Brush brush, RectangleF rect) /// /// Fills the interior of a rectangle with a . /// - public void FillRectangle(Brush brush, float x, float y, float width, float height) + public void FillRectangle(Brush brush!!, float x, float y, float width, float height) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - CheckErrorStatus(Gdip.GdipFillRectangle( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -1178,11 +1055,8 @@ public void FillRectangle(Brush brush, Rectangle rect) /// /// Fills the interior of a rectangle with a . /// - public void FillRectangle(Brush brush, int x, int y, int width, int height) + public void FillRectangle(Brush brush!!, int x, int y, int width, int height) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - CheckErrorStatus(Gdip.GdipFillRectangleI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -1192,13 +1066,8 @@ public void FillRectangle(Brush brush, int x, int y, int width, int height) /// /// Fills the interiors of a series of rectangles with a . /// - public unsafe void FillRectangles(Brush brush, RectangleF[] rects) + public unsafe void FillRectangles(Brush brush!!, RectangleF[] rects!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (rects == null) - throw new ArgumentNullException(nameof(rects)); - fixed (RectangleF* r = rects) { CheckErrorStatus(Gdip.GdipFillRectangles( @@ -1211,13 +1080,8 @@ public unsafe void FillRectangles(Brush brush, RectangleF[] rects) /// /// Fills the interiors of a series of rectangles with a . /// - public unsafe void FillRectangles(Brush brush, Rectangle[] rects) + public unsafe void FillRectangles(Brush brush!!, Rectangle[] rects!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (rects == null) - throw new ArgumentNullException(nameof(rects)); - fixed (Rectangle* r = rects) { CheckErrorStatus(Gdip.GdipFillRectanglesI( @@ -1238,13 +1102,8 @@ public void FillPolygon(Brush brush, PointF[] points) /// /// Fills the interior of a polygon defined by an array of points. /// - public unsafe void FillPolygon(Brush brush, PointF[] points, FillMode fillMode) + public unsafe void FillPolygon(Brush brush!!, PointF[] points!!, FillMode fillMode) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipFillPolygon( @@ -1266,13 +1125,8 @@ public void FillPolygon(Brush brush, Point[] points) /// /// Fills the interior of a polygon defined by an array of points. /// - public unsafe void FillPolygon(Brush brush, Point[] points, FillMode fillMode) + public unsafe void FillPolygon(Brush brush!!, Point[] points!!, FillMode fillMode) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipFillPolygonI( @@ -1294,11 +1148,8 @@ public void FillEllipse(Brush brush, RectangleF rect) /// /// Fills the interior of an ellipse defined by a bounding rectangle. /// - public void FillEllipse(Brush brush, float x, float y, float width, float height) + public void FillEllipse(Brush brush!!, float x, float y, float width, float height) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - CheckErrorStatus(Gdip.GdipFillEllipse( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -1316,11 +1167,8 @@ public void FillEllipse(Brush brush, Rectangle rect) /// /// Fills the interior of an ellipse defined by a bounding rectangle. /// - public void FillEllipse(Brush brush, int x, int y, int width, int height) + public void FillEllipse(Brush brush!!, int x, int y, int width, int height) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - CheckErrorStatus(Gdip.GdipFillEllipseI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -1350,11 +1198,8 @@ public void FillPie(Brush brush, RectangleF rect, float startAngle, float sweepA /// /// Fills the interior of a pie section defined by an ellipse and two radial lines. /// - public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle) + public void FillPie(Brush brush!!, float x, float y, float width, float height, float startAngle, float sweepAngle) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - CheckErrorStatus(Gdip.GdipFillPie( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -1366,11 +1211,8 @@ public void FillPie(Brush brush, float x, float y, float width, float height, fl /// /// Fills the interior of a pie section defined by an ellipse and two radial lines. /// - public void FillPie(Brush brush, int x, int y, int width, int height, int startAngle, int sweepAngle) + public void FillPie(Brush brush!!, int x, int y, int width, int height, int startAngle, int sweepAngle) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - CheckErrorStatus(Gdip.GdipFillPieI( new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), @@ -1382,13 +1224,8 @@ public void FillPie(Brush brush, int x, int y, int width, int height, int startA /// /// Fills the interior a closed curve defined by an array of points. /// - public unsafe void FillClosedCurve(Brush brush, PointF[] points) + public unsafe void FillClosedCurve(Brush brush!!, PointF[] points!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurve( @@ -1406,13 +1243,8 @@ public void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode) FillClosedCurve(brush, points, fillmode, 0.5f); } - public unsafe void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode, float tension) + public unsafe void FillClosedCurve(Brush brush!!, PointF[] points!!, FillMode fillmode, float tension) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurve2( @@ -1427,13 +1259,8 @@ public unsafe void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmo /// /// Fills the interior a closed curve defined by an array of points. /// - public unsafe void FillClosedCurve(Brush brush, Point[] points) + public unsafe void FillClosedCurve(Brush brush!!, Point[] points!!) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurveI( @@ -1448,13 +1275,8 @@ public void FillClosedCurve(Brush brush, Point[] points, FillMode fillmode) FillClosedCurve(brush, points, fillmode, 0.5f); } - public unsafe void FillClosedCurve(Brush brush, Point[] points, FillMode fillmode, float tension) + public unsafe void FillClosedCurve(Brush brush!!, Point[] points!!, FillMode fillmode, float tension) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipFillClosedCurve2I( @@ -1494,10 +1316,8 @@ public void DrawString(string? s, Font font, Brush brush, RectangleF layoutRecta DrawString(s, font, brush, layoutRectangle, null); } - public void DrawString(string? s, Font font, Brush brush, RectangleF layoutRectangle, StringFormat? format) + public void DrawString(string? s, Font font, Brush brush!!, RectangleF layoutRectangle, StringFormat? format) { - if (brush == null) - throw new ArgumentNullException(nameof(brush)); if (string.IsNullOrEmpty(s)) return; if (font == null) @@ -1654,11 +1474,8 @@ public void DrawImage(Image image, PointF point) DrawImage(image, point.X, point.Y); } - public void DrawImage(Image image, float x, float y) + public void DrawImage(Image image!!, float x, float y) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImage( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), x, y); @@ -1672,11 +1489,8 @@ public void DrawImage(Image image, RectangleF rect) DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height); } - public void DrawImage(Image image, float x, float y, float width, float height) + public void DrawImage(Image image!!, float x, float y, float width, float height) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1692,11 +1506,8 @@ public void DrawImage(Image image, Point point) DrawImage(image, point.X, point.Y); } - public void DrawImage(Image image, int x, int y) + public void DrawImage(Image image!!, int x, int y) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1711,11 +1522,8 @@ public void DrawImage(Image image, Rectangle rect) DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height); } - public void DrawImage(Image image, int x, int y, int width, int height) + public void DrawImage(Image image!!, int x, int y, int width, int height) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1746,11 +1554,8 @@ public void DrawImageUnscaled(Image image, int x, int y, int width, int height) DrawImage(image, x, y); } - public void DrawImageUnscaledAndClipped(Image image, Rectangle rect) + public void DrawImageUnscaledAndClipped(Image image!!, Rectangle rect) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int width = Math.Min(rect.Width, image.Width); int height = Math.Min(rect.Height, image.Height); @@ -1769,13 +1574,8 @@ public void DrawImageUnscaledAndClipped(Image image, Rectangle rect) // // @notes Perspective blt only works for bitmap images. - public unsafe void DrawImage(Image image, PointF[] destPoints) + public unsafe void DrawImage(Image image!!, PointF[] destPoints!!) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - if (image == null) - throw new ArgumentNullException(nameof(image)); - int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); @@ -1792,13 +1592,8 @@ public unsafe void DrawImage(Image image, PointF[] destPoints) } } - public unsafe void DrawImage(Image image, Point[] destPoints) + public unsafe void DrawImage(Image image!!, Point[] destPoints!!) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - if (image == null) - throw new ArgumentNullException(nameof(image)); - int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); @@ -1815,11 +1610,8 @@ public unsafe void DrawImage(Image image, Point[] destPoints) } } - public void DrawImage(Image image, float x, float y, RectangleF srcRect, GraphicsUnit srcUnit) + public void DrawImage(Image image!!, float x, float y, RectangleF srcRect, GraphicsUnit srcUnit) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImagePointRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1831,11 +1623,8 @@ public void DrawImage(Image image, float x, float y, RectangleF srcRect, Graphic CheckErrorStatus(status); } - public void DrawImage(Image image, int x, int y, Rectangle srcRect, GraphicsUnit srcUnit) + public void DrawImage(Image image!!, int x, int y, Rectangle srcRect, GraphicsUnit srcUnit) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImagePointRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1847,11 +1636,8 @@ public void DrawImage(Image image, int x, int y, Rectangle srcRect, GraphicsUnit CheckErrorStatus(status); } - public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit) + public void DrawImage(Image image!!, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageRectRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1866,11 +1652,8 @@ public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, Grap CheckErrorStatus(status); } - public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit) + public void DrawImage(Image image!!, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageRectRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -1885,13 +1668,8 @@ public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, Graphi CheckErrorStatus(status); } - public unsafe void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit) + public unsafe void DrawImage(Image image!!, PointF[] destPoints!!, RectangleF srcRect, GraphicsUnit srcUnit) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - if (image == null) - throw new ArgumentNullException(nameof(image)); - int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); @@ -1930,19 +1708,14 @@ public void DrawImage( } public unsafe void DrawImage( - Image image, - PointF[] destPoints, + Image image!!, + PointF[] destPoints!!, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback, int callbackData) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - if (image == null) - throw new ArgumentNullException(nameof(image)); - int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); @@ -1991,19 +1764,14 @@ public void DrawImage( } public unsafe void DrawImage( - Image image, - Point[] destPoints, + Image image!!, + Point[] destPoints!!, Rectangle srcRect, GraphicsUnit srcUnit, ImageAttributes? imageAttr, DrawImageAbort? callback, int callbackData) { - if (destPoints == null) - throw new ArgumentNullException(nameof(destPoints)); - if (image == null) - throw new ArgumentNullException(nameof(image)); - int count = destPoints.Length; if (count != 3 && count != 4) throw new ArgumentException(SR.GdiplusDestPointsInvalidLength); @@ -2065,7 +1833,7 @@ public void DrawImage( } public void DrawImage( - Image image, + Image image!!, Rectangle destRect, float srcX, float srcY, @@ -2076,9 +1844,6 @@ public void DrawImage( DrawImageAbort? callback, IntPtr callbackData) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageRectRect( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -2133,7 +1898,7 @@ public void DrawImage( } public void DrawImage( - Image image, + Image image!!, Rectangle destRect, int srcX, int srcY, @@ -2144,9 +1909,6 @@ public void DrawImage( DrawImageAbort? callback, IntPtr callbackData) { - if (image == null) - throw new ArgumentNullException(nameof(image)); - int status = Gdip.GdipDrawImageRectRectI( new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage), @@ -2172,13 +1934,8 @@ public void DrawLine(Pen pen, PointF pt1, PointF pt2) /// /// Draws a series of line segments that connect an array of points. /// - public unsafe void DrawLines(Pen pen, PointF[] points) + public unsafe void DrawLines(Pen pen!!, PointF[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (PointF* p = points) { CheckErrorStatus(Gdip.GdipDrawLines( @@ -2192,11 +1949,8 @@ public unsafe void DrawLines(Pen pen, PointF[] points) /// /// Draws a line connecting the two specified points. /// - public void DrawLine(Pen pen, int x1, int y1, int x2, int y2) + public void DrawLine(Pen pen!!, int x1, int y1, int x2, int y2) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - CheckErrorStatus(Gdip.GdipDrawLineI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2)); } @@ -2211,13 +1965,8 @@ public void DrawLine(Pen pen, Point pt1, Point pt2) /// /// Draws a series of line segments that connect an array of points. /// - public unsafe void DrawLines(Pen pen, Point[] points) + public unsafe void DrawLines(Pen pen!!, Point[] points!!) { - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - if (points == null) - throw new ArgumentNullException(nameof(points)); - fixed (Point* p = points) { CheckErrorStatus(Gdip.GdipDrawLinesI( @@ -2443,11 +2192,8 @@ public void EnumerateMetafile( EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, callbackData, null); } - public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, PointF[] pts) + public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, PointF[] pts!!) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); - fixed (PointF* p = pts) { Gdip.CheckStatus(Gdip.GdipTransformPoints( @@ -2459,11 +2205,8 @@ public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace sr } } - public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, Point[] pts) + public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, Point[] pts!!) { - if (pts == null) - throw new ArgumentNullException(nameof(pts)); - fixed (Point* p = pts) { Gdip.CheckStatus(Gdip.GdipTransformPointsI( diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs index 9cb8421417051b..ba97e2636f8e3b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs @@ -144,11 +144,8 @@ public Icon(Icon original, int width, int height) { } - public Icon(Icon original, Size size) + public Icon(Icon original!!, Size size) { - if (original == null) - throw new ArgumentNullException(nameof(original)); - iconSize = size; iconDir = original.iconDir; @@ -238,11 +235,8 @@ public Icon(string fileName) } } - public Icon(Type type, string resource) + public Icon(Type type, string resource!!) { - if (resource == null) - throw new ArgumentNullException(nameof(resource)); - // For compatibility with the .NET Framework if (type == null) throw new NullReferenceException(); @@ -309,10 +303,8 @@ void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) si.AddValue("IconData", ms.ToArray()); // Do not rename (binary serialization) } - public static Icon ExtractAssociatedIcon(string filePath) + public static Icon ExtractAssociatedIcon(string filePath!!) { - if (filePath == null) - throw new ArgumentNullException(nameof(filePath)); if (string.IsNullOrEmpty(filePath)) throw new ArgumentException(SR.NullOrEmptyPath, nameof(filePath)); if (!File.Exists(filePath)) @@ -712,11 +704,8 @@ public int Width Dispose(); } - private void InitFromStreamWithSize(Stream stream, int width, int height) + private void InitFromStreamWithSize(Stream stream!!, int width, int height) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - if (stream.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(stream))); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs index 1ee3b3705ecf1d..885e2668c40f00 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs @@ -82,13 +82,8 @@ public Icon(Icon original, Size size) : this(original, size.Width, size.Height) { } - public Icon(Icon original, int width, int height) : this() + public Icon(Icon original!!, int width, int height) : this() { - if (original == null) - { - throw new ArgumentNullException(nameof(original)); - } - _iconData = original._iconData; if (_iconData == null) @@ -102,11 +97,8 @@ public Icon(Icon original, int width, int height) : this() } } - public Icon(Type type, string resource) : this() + public Icon(Type type, string resource!!) : this() { - if (resource == null) - throw new ArgumentNullException(nameof(resource)); - Stream? stream = type.Module.Assembly.GetManifestResourceStream(type, resource); if (stream == null) { @@ -126,13 +118,8 @@ public Icon(Stream stream, Size size) : this(stream, size.Width, size.Height) { } - public Icon(Stream stream, int width, int height) : this() + public Icon(Stream stream!!, int width, int height) : this() { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - _iconData = new byte[(int)stream.Length]; stream.Read(_iconData, 0, _iconData.Length); Initialize(width, height); @@ -163,13 +150,8 @@ void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) public static Icon? ExtractAssociatedIcon(string filePath) => ExtractAssociatedIcon(filePath, 0); - private static unsafe Icon? ExtractAssociatedIcon(string filePath, int index) + private static unsafe Icon? ExtractAssociatedIcon(string filePath!!, int index) { - if (filePath == null) - { - throw new ArgumentNullException(nameof(filePath)); - } - if (string.IsNullOrEmpty(filePath)) throw new ArgumentException(SR.NullOrEmptyPath, nameof(filePath)); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs index c12a3695349381..27b994fa9d4727 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs @@ -57,20 +57,14 @@ public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, b return LoadFromStream(stream, false); } - internal static Image LoadFromStream(Stream stream, bool keepAlive) + internal static Image LoadFromStream(Stream stream!!, bool keepAlive) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - Image img = CreateImageObject(InitializeFromStream(stream)); return img; } - private protected static IntPtr InitializeFromStream(Stream stream) + private protected static IntPtr InitializeFromStream(Stream stream!!) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - // Unix, with libgdiplus // We use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream @@ -159,11 +153,8 @@ public void Save(string filename, ImageFormat format) Save(filename, encoder, null); } - public void Save(string filename, ImageCodecInfo encoder, EncoderParameters? encoderParams) + public void Save(string filename!!, ImageCodecInfo encoder, EncoderParameters? encoderParams) { - if (filename == null) - throw new ArgumentNullException(nameof(filename)); - ThrowIfDirectoryDoesntExist(filename); int st; @@ -291,12 +282,8 @@ internal ColorPalette retrieveGDIPalette() } } - internal void storeGDIPalette(ColorPalette palette) + internal void storeGDIPalette(ColorPalette palette!!) { - if (palette == null) - { - throw new ArgumentNullException(nameof(palette)); - } IntPtr palette_data = palette.ConvertToMemory(); if (palette_data == IntPtr.Zero) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs index b561398144222e..2e625f36e9b557 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs @@ -18,11 +18,8 @@ public abstract partial class Image private string allocationSite = Graphics.GetAllocationStack(); #endif - public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData) + public static Image FromStream(Stream stream!!, bool useEmbeddedColorManagement, bool validateImageData) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - IntPtr image = LoadGdipImageFromStream(new GPStream(stream), useEmbeddedColorManagement); if (validateImageData) @@ -114,11 +111,8 @@ protected virtual void Dispose(bool disposing) /// /// Saves this to the specified file in the specified format. /// - public void Save(string filename, ImageFormat format) + public void Save(string filename, ImageFormat format!!) { - if (format == null) - throw new ArgumentNullException(nameof(format)); - ImageCodecInfo? codec = format.FindEncoder(); if (codec == null) @@ -130,13 +124,8 @@ public void Save(string filename, ImageFormat format) /// /// Saves this to the specified file in the specified format and with the specified encoder parameters. /// - public void Save(string filename, ImageCodecInfo encoder, EncoderParameters? encoderParams) + public void Save(string filename!!, ImageCodecInfo encoder!!, EncoderParameters? encoderParams) { - if (filename == null) - throw new ArgumentNullException(nameof(filename)); - if (encoder == null) - throw new ArgumentNullException(nameof(encoder)); - ThrowIfDirectoryDoesntExist(filename); IntPtr encoderParamsMemory = IntPtr.Zero; @@ -199,11 +188,8 @@ private void Save(MemoryStream stream) /// /// Saves this to the specified stream in the specified format. /// - public void Save(Stream stream, ImageFormat format) + public void Save(Stream stream, ImageFormat format!!) { - if (format == null) - throw new ArgumentNullException(nameof(format)); - ImageCodecInfo codec = format.FindEncoder()!; Save(stream, codec, null); } @@ -211,13 +197,8 @@ public void Save(Stream stream, ImageFormat format) /// /// Saves this to the specified stream in the specified format. /// - public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters? encoderParams) + public void Save(Stream stream!!, ImageCodecInfo encoder!!, EncoderParameters? encoderParams) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - if (encoder == null) - throw new ArgumentNullException(nameof(encoder)); - IntPtr encoderParamsMemory = IntPtr.Zero; if (encoderParams != null) @@ -290,12 +271,9 @@ public void SaveAdd(EncoderParameters? encoderParams) /// /// Adds an to the specified . /// - public void SaveAdd(Image image, EncoderParameters? encoderParams) + public void SaveAdd(Image image!!, EncoderParameters? encoderParams) { IntPtr encoder = IntPtr.Zero; - - if (image == null) - throw new ArgumentNullException(nameof(image)); if (encoderParams != null) encoder = encoderParams.ConvertToMemory(); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs index 06ce78264e8c74..cca9e7cd64cfcb 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs @@ -136,11 +136,8 @@ internal void GraphicsDisposed() // (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image) internal Metafile(IntPtr ptr, Stream stream) => SetNativeImage(ptr); - public Metafile(Stream stream) + public Metafile(Stream stream!!) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - // With libgdiplus we use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, seekToOrigin: false); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs index 500ab7f54e6a22..43e48a864f39ab 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs @@ -26,13 +26,8 @@ public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) : /// /// Initializes a new instance of the class from the specified stream. /// - public unsafe Metafile(Stream stream) + public unsafe Metafile(Stream stream!!) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - using DrawingCom.IStreamWrapper streamWrapper = DrawingCom.GetComWrapper(new GPStream(stream)); IntPtr metafile = IntPtr.Zero; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs index 524be173b52cf8..4758abd0ec59a3 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs @@ -129,13 +129,8 @@ public void SetSize(ulong value) _dataStream.SetLength(checked((long)value)); } - public unsafe void Stat(Interop.Ole32.STATSTG* pstatstg, Interop.Ole32.STATFLAG grfStatFlag) + public unsafe void Stat(Interop.Ole32.STATSTG* pstatstg!!, Interop.Ole32.STATFLAG grfStatFlag) { - if (pstatstg == null) - { - throw new ArgumentNullException(nameof(pstatstg)); - } - *pstatstg = new Interop.Ole32.STATSTG { cbSize = (ulong)_dataStream.Length, 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 cf22eae646cd40..2f953d2250c22d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs @@ -84,13 +84,8 @@ public Pen(Brush brush) : this(brush, (float)1.0) /// /// Initializes a new instance of the class with the specified and width. /// - public Pen(Brush brush, float width) + public Pen(Brush brush!!, float width) { - if (brush == null) - { - throw new ArgumentNullException(nameof(brush)); - } - IntPtr pen; int status = Gdip.GdipCreatePen2(new HandleRef(brush, brush.NativeBrush), width, diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs index 7354b6adbf0644..2982ca860d8076 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/MarginsConverter.cs @@ -91,12 +91,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// type is string. If this cannot convert to the desitnation 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!!) { - if (destinationType == null) - { - throw new ArgumentNullException(nameof(destinationType)); - } if (value is Margins margins) { if (destinationType == typeof(string)) @@ -144,13 +140,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina /// for the object. This is useful for objects that are immutable, but still /// want to provide changable properties. /// - public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues) + public override object CreateInstance(ITypeDescriptorContext? context, IDictionary propertyValues!!) { - if (propertyValues == null) - { - throw new ArgumentNullException(nameof(propertyValues)); - } - object? left = propertyValues["Left"]; object? right = propertyValues["Right"]; object? top = propertyValues["Top"]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs index d53c41d5e528c7..50eb520a9c1afe 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs @@ -36,20 +36,14 @@ public Region(Rectangle rect) SetNativeRegion(region); } - public Region(GraphicsPath path) + public Region(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCreateRegionPath(new HandleRef(path, path._nativePath), out IntPtr region)); SetNativeRegion(region); } - public Region(RegionData rgnData) + public Region(RegionData rgnData!!) { - if (rgnData == null) - throw new ArgumentNullException(nameof(rgnData)); - Gdip.CheckStatus(Gdip.GdipCreateRegionRgnData( rgnData.Data, rgnData.Data.Length, @@ -136,19 +130,13 @@ public void Intersect(Rectangle rect) Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Intersect)); } - public void Intersect(GraphicsPath path) + public void Intersect(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Intersect)); } - public void Intersect(Region region) + public void Intersect(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Intersect)); } @@ -162,19 +150,13 @@ public void Union(Rectangle rect) Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Union)); } - public void Union(GraphicsPath path) + public void Union(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Union)); } - public void Union(Region region) + public void Union(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Union)); } @@ -188,19 +170,13 @@ public void Xor(Rectangle rect) Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Xor)); } - public void Xor(GraphicsPath path) + public void Xor(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Xor)); } - public void Xor(Region region) + public void Xor(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Xor)); } @@ -214,22 +190,16 @@ public void Exclude(Rectangle rect) Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Exclude)); } - public void Exclude(GraphicsPath path) + public void Exclude(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCombineRegionPath( new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Exclude)); } - public void Exclude(Region region) + public void Exclude(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipCombineRegionRegion( new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), @@ -246,19 +216,13 @@ public void Complement(Rectangle rect) Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Complement)); } - public void Complement(GraphicsPath path) + public void Complement(GraphicsPath path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Complement)); } - public void Complement(Region region) + public void Complement(Region region!!) { - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Complement)); } @@ -272,59 +236,39 @@ public void Translate(int dx, int dy) Gdip.CheckStatus(Gdip.GdipTranslateRegionI(new HandleRef(this, NativeRegion), dx, dy)); } - public void Transform(Matrix matrix) + public void Transform(Matrix matrix!!) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); - Gdip.CheckStatus(Gdip.GdipTransformRegion( new HandleRef(this, NativeRegion), new HandleRef(matrix, matrix.NativeMatrix))); } - public RectangleF GetBounds(Graphics g) + public RectangleF GetBounds(Graphics g!!) { - if (g == null) - throw new ArgumentNullException(nameof(g)); - Gdip.CheckStatus(Gdip.GdipGetRegionBounds(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out RectangleF bounds)); return bounds; } - public IntPtr GetHrgn(Graphics g) + public IntPtr GetHrgn(Graphics g!!) { - if (g == null) - throw new ArgumentNullException(nameof(g)); - Gdip.CheckStatus(Gdip.GdipGetRegionHRgn(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out IntPtr hrgn)); return hrgn; } - public bool IsEmpty(Graphics g) + public bool IsEmpty(Graphics g!!) { - if (g == null) - throw new ArgumentNullException(nameof(g)); - Gdip.CheckStatus(Gdip.GdipIsEmptyRegion(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out int isEmpty)); return isEmpty != 0; } - public bool IsInfinite(Graphics g) + public bool IsInfinite(Graphics g!!) { - if (g == null) - throw new ArgumentNullException(nameof(g)); - Gdip.CheckStatus(Gdip.GdipIsInfiniteRegion(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out int isInfinite)); return isInfinite != 0; } - public bool Equals(Region region, Graphics g) + public bool Equals(Region region!!, Graphics g!!) { - if (g == null) - throw new ArgumentNullException(nameof(g)); - if (region == null) - throw new ArgumentNullException(nameof(region)); - Gdip.CheckStatus(Gdip.GdipIsEqualRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), new HandleRef(g, g.NativeGraphics), out int isEqual)); return isEqual != 0; } @@ -407,11 +351,8 @@ public bool IsVisible(Rectangle rect, Graphics? g) return isVisible != 0; } - public unsafe RectangleF[] GetRegionScans(Matrix matrix) + public unsafe RectangleF[] GetRegionScans(Matrix matrix!!) { - if (matrix == null) - throw new ArgumentNullException(nameof(matrix)); - Gdip.CheckStatus(Gdip.GdipGetRegionScansCount( new HandleRef(this, NativeRegion), out int count, diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs index e233fe56798f39..fc910b3ce95894 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs @@ -53,13 +53,8 @@ public StringFormat(StringFormatFlags options, int language) /// Initializes a new instance of the class from the specified /// existing . /// - public StringFormat(StringFormat format) + public StringFormat(StringFormat format!!) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - int status = Gdip.GdipCloneStringFormat(new HandleRef(format, format.nativeFormat), out nativeFormat); if (status != Gdip.Ok) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs index 53d9ea5c117f70..9835d63d78ca1c 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs @@ -22,13 +22,8 @@ public TextureBrush(Image bitmap) : this(bitmap, WrapMode.Tile) { } - public TextureBrush(Image image, WrapMode wrapMode) + public TextureBrush(Image image!!, WrapMode wrapMode) { - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } - if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) { throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); @@ -43,13 +38,8 @@ public TextureBrush(Image image, WrapMode wrapMode) SetNativeBrushInternal(brush); } - public TextureBrush(Image image, WrapMode wrapMode, RectangleF dstRect) + public TextureBrush(Image image!!, WrapMode wrapMode, RectangleF dstRect) { - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } - if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) { throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); @@ -68,13 +58,8 @@ public TextureBrush(Image image, WrapMode wrapMode, RectangleF dstRect) SetNativeBrushInternal(brush); } - public TextureBrush(Image image, WrapMode wrapMode, Rectangle dstRect) + public TextureBrush(Image image!!, WrapMode wrapMode, Rectangle dstRect) { - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } - if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp) { throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); @@ -95,13 +80,8 @@ public TextureBrush(Image image, WrapMode wrapMode, Rectangle dstRect) public TextureBrush(Image image, RectangleF dstRect) : this(image, dstRect, null) { } - public TextureBrush(Image image, RectangleF dstRect, ImageAttributes? imageAttr) + public TextureBrush(Image image!!, RectangleF dstRect, ImageAttributes? imageAttr) { - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } - IntPtr brush; int status = Gdip.GdipCreateTextureIA(new HandleRef(image, image.nativeImage), new HandleRef(imageAttr, (imageAttr == null) ? @@ -118,13 +98,8 @@ public TextureBrush(Image image, RectangleF dstRect, ImageAttributes? imageAttr) public TextureBrush(Image image, Rectangle dstRect) : this(image, dstRect, null) { } - public TextureBrush(Image image, Rectangle dstRect, ImageAttributes? imageAttr) + public TextureBrush(Image image!!, Rectangle dstRect, ImageAttributes? imageAttr) { - if (image == null) - { - throw new ArgumentNullException(nameof(image)); - } - IntPtr brush; int status = Gdip.GdipCreateTextureIAI(new HandleRef(image, image.nativeImage), new HandleRef(imageAttr, (imageAttr == null) ? @@ -218,13 +193,8 @@ public void ResetTransform() public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); - public void MultiplyTransform(Matrix matrix, MatrixOrder order) + public void MultiplyTransform(Matrix matrix!!, MatrixOrder order) { - if (matrix == null) - { - throw new ArgumentNullException(nameof(matrix)); - } - // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws // with the libgdiplus backend. Simulate a nop for compatability with GDI+. if (matrix.NativeMatrix == IntPtr.Zero) 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 a29ad2ba063048..3c300f5e1fb041 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,11 +30,8 @@ public sealed partial class AsnWriter /// /// /// - public void WriteEnumeratedValue(Enum value, Asn1Tag? tag = null) + public void WriteEnumeratedValue(Enum value!!, Asn1Tag? tag = null) { - if (value == 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 424e484abef2b9..149f2dc8e26288 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,11 +32,8 @@ public sealed partial class AsnWriter /// /// is . /// - public void WriteNamedBitList(Enum value, Asn1Tag? tag = null) + public void WriteNamedBitList(Enum value!!, Asn1Tag? tag = null) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - CheckUniversalTag(tag, UniversalTagNumber.BitString); WriteNamedBitList(tag, value.GetType(), value); @@ -89,11 +86,8 @@ 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 == 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 b9b77fad02eaf5..d458f988e839e8 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,11 +28,8 @@ public sealed partial class AsnWriter /// /// is . /// - public void WriteObjectIdentifier(string oidValue, Asn1Tag? tag = null) + public void WriteObjectIdentifier(string oidValue!!, Asn1Tag? tag = null) { - if (oidValue == 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 7f0ab728f6e77f..032c3ffec5691a 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,11 +36,8 @@ 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 == 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 9938ddad4ac2cd..de4dc8ef0fd248 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,11 +223,8 @@ 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 == null) - throw new ArgumentNullException(nameof(other)); - return EncodeAsSpan().SequenceEqual(other.EncodeAsSpan()); } @@ -381,11 +378,8 @@ 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 == 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 2e600d99dad32a..39e0aeb32d2546 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,13 +22,8 @@ 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()); } @@ -106,13 +101,8 @@ 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.Globalization/tests/CultureInfo/GetCultureInfo.cs b/src/libraries/System.Globalization/tests/CultureInfo/GetCultureInfo.cs index 5a5e3dada218b1..8312abdb3fe9b7 100644 --- a/src/libraries/System.Globalization/tests/CultureInfo/GetCultureInfo.cs +++ b/src/libraries/System.Globalization/tests/CultureInfo/GetCultureInfo.cs @@ -209,7 +209,7 @@ public void TestAllowInvariantCultureOnly(bool enableInvariant, bool predefinedC Assert.NotNull(exception); Assert.IsType(exception); Assert.Equal("collection", (exception as ArgumentNullException).ParamName); - Assert.Equal("The collection argument is null. (Parameter 'collection')", exception.Message); + Assert.Equal("Value cannot be null. (Parameter 'collection')", exception.Message); } else { 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 73ecccf89262b7..cda66334319f2b 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,11 +25,8 @@ 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) { - if (stream == null) - throw new ArgumentNullException(nameof(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 eb908ed66f0179..6631352d278782 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,11 +181,8 @@ 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) { - if (sourceArchiveFileName == null) - throw new ArgumentNullException(nameof(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 c9199a97f2a895..8e780cc7793a23 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,18 +77,9 @@ 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) { - if (destination == null) - throw new ArgumentNullException(nameof(destination)); - - if (sourceFileName == null) - throw new ArgumentNullException(nameof(sourceFileName)); - - if (entryName == null) - throw new ArgumentNullException(nameof(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 3dd751dce8ddf6..ed01fa2689e982 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,14 +65,8 @@ 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) { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - if (destinationDirectoryName == null) - throw new ArgumentNullException(nameof(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 fe725937441e24..ef6192cb903166 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,14 +60,8 @@ 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) { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - if (destinationFileName == null) - throw new ArgumentNullException(nameof(destinationFileName)); - // Rely on FileStream's ctor for further checking destinationFileName parameter FileMode fMode = overwrite ? FileMode.Create : FileMode.CreateNew; @@ -94,14 +88,8 @@ public static void ExtractToFile(this ZipArchiveEntry source, string destination 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) { - if (source == null) - throw new ArgumentNullException(nameof(source)); - - if (destinationDirectoryName == null) - throw new ArgumentNullException(nameof(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 ca31e978b332f0..949e1d7385d9e0 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,10 +20,8 @@ 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) { - if (stream == null) - throw new ArgumentNullException(nameof(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 a12f16f61080d4..858ba4fc84e5eb 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,11 +49,8 @@ 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) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - switch (mode) { case CompressionMode.Decompress: @@ -78,11 +75,8 @@ internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int /// /// 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) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - InitializeDeflater(stream, leaveOpen, windowBits, compressionLevel); } 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 5d68416b3b25da..3adf8a65702567 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,11 +117,8 @@ 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) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - EntryNameAndCommentEncoding = entryNameEncoding; Stream? extraTempStream = null; @@ -341,11 +338,8 @@ 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!!) { - if (entryName == null) - throw new ArgumentNullException(nameof(entryName)); - if (_mode == ZipArchiveMode.Create) throw new NotSupportedException(SR.EntriesInCreateMode); @@ -392,11 +386,8 @@ private set } } - private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compressionLevel) + private ZipArchiveEntry DoCreateEntry(string entryName!!, CompressionLevel? compressionLevel) { - if (entryName == null) - throw new ArgumentNullException(nameof(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 0fc0de2a59b911..8aabc90911c8df 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,69 +10,34 @@ namespace System.IO { public static partial class FileSystemAclExtensions { - public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo) + public static DirectorySecurity GetAccessControl(this DirectoryInfo directoryInfo!!) { - if (directoryInfo == null) - { - throw new ArgumentNullException(nameof(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) { - if (directoryInfo == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (directorySecurity == null) - { - throw new ArgumentNullException(nameof(directorySecurity)); - } - string fullPath = Path.GetFullPath(directoryInfo.FullName); directorySecurity.Persist(fullPath); } - public static FileSecurity GetAccessControl(this FileInfo fileInfo) + public static FileSecurity GetAccessControl(this FileInfo fileInfo!!) { - if (fileInfo == null) - { - throw new ArgumentNullException(nameof(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) { - if (fileInfo == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (fileInfo == null) - { - throw new ArgumentNullException(nameof(fileInfo)); - } - - if (fileSecurity == null) - { - throw new ArgumentNullException(nameof(fileSecurity)); - } - string fullPath = Path.GetFullPath(fileInfo.FullName); // Appropriate security check should be done for us by FileSecurity. fileSecurity.Persist(fullPath); @@ -84,13 +49,8 @@ public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSec /// 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!!) { - if (fileStream == null) - { - throw new ArgumentNullException(nameof(fileStream)); - } - SafeFileHandle handle = fileStream.SafeFileHandle; if (handle.IsClosed) { @@ -107,18 +67,8 @@ 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!!) { - if (fileStream == null) - { - throw new ArgumentNullException(nameof(fileStream)); - } - - if (fileSecurity == null) - { - throw new ArgumentNullException(nameof(fileSecurity)); - } - SafeFileHandle handle = fileStream.SafeFileHandle; if (handle.IsClosed) { @@ -135,18 +85,8 @@ public static void SetAccessControl(this FileStream fileStream, FileSecurity fil /// 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!!) { - if (directoryInfo == null) - { - throw new ArgumentNullException(nameof(directoryInfo)); - } - - if (directorySecurity == null) - { - throw new ArgumentNullException(nameof(directorySecurity)); - } - FileSystem.CreateDirectory(directoryInfo.FullName, directorySecurity.GetSecurityDescriptorBinaryForm()); } @@ -170,13 +110,8 @@ public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity di /// 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) { - if (fileInfo == null) - { - throw new ArgumentNullException(nameof(fileInfo)); - } - // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; @@ -242,9 +177,8 @@ public static FileStream Create(this FileInfo fileInfo, FileMode mode, FileSyste /// 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 a04d60120c7417..a7edee77e2375c 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,13 +17,9 @@ protected DirectoryObjectSecurity() return; } - protected DirectoryObjectSecurity(CommonSecurityDescriptor securityDescriptor) + protected DirectoryObjectSecurity(CommonSecurityDescriptor securityDescriptor!!) : base(securityDescriptor) { - if (securityDescriptor == null) - { - throw new ArgumentNullException(nameof(securityDescriptor)); - } } #region Private Methods @@ -520,13 +516,8 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi #region Public Methods - protected void AddAccessRule(ObjectAccessRule rule) + protected void AddAccessRule(ObjectAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -541,13 +532,8 @@ protected void AddAccessRule(ObjectAccessRule rule) return; } - protected void SetAccessRule(ObjectAccessRule rule) + protected void SetAccessRule(ObjectAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -560,13 +546,8 @@ protected void SetAccessRule(ObjectAccessRule rule) } } - protected void ResetAccessRule(ObjectAccessRule rule) + protected void ResetAccessRule(ObjectAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -579,13 +560,8 @@ protected void ResetAccessRule(ObjectAccessRule rule) } } - protected bool RemoveAccessRule(ObjectAccessRule rule) + protected bool RemoveAccessRule(ObjectAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -603,13 +579,8 @@ protected bool RemoveAccessRule(ObjectAccessRule rule) } } - protected void RemoveAccessRuleAll(ObjectAccessRule rule) + protected void RemoveAccessRuleAll(ObjectAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -627,13 +598,8 @@ protected void RemoveAccessRuleAll(ObjectAccessRule rule) } } - protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) + protected void RemoveAccessRuleSpecific(ObjectAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - if (SecurityDescriptor == null) { return; @@ -651,13 +617,8 @@ protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) } } - protected void AddAuditRule(ObjectAuditRule rule) + protected void AddAuditRule(ObjectAuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -670,13 +631,8 @@ protected void AddAuditRule(ObjectAuditRule rule) } } - protected void SetAuditRule(ObjectAuditRule rule) + protected void SetAuditRule(ObjectAuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -689,13 +645,8 @@ protected void SetAuditRule(ObjectAuditRule rule) } } - protected bool RemoveAuditRule(ObjectAuditRule rule) + protected bool RemoveAuditRule(ObjectAuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -708,13 +659,8 @@ protected bool RemoveAuditRule(ObjectAuditRule rule) } } - protected void RemoveAuditRuleAll(ObjectAuditRule rule) + protected void RemoveAuditRuleAll(ObjectAuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -727,13 +673,8 @@ protected void RemoveAuditRuleAll(ObjectAuditRule rule) } } - protected void RemoveAuditRuleSpecific(ObjectAuditRule rule) + protected void RemoveAuditRuleSpecific(ObjectAuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(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 27cd96a664a55b..50cf85d690b81d 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,11 +162,8 @@ public void ResetAccessRule(FileSystemAccessRule rule) base.ResetAccessRule(rule); } - public bool RemoveAccessRule(FileSystemAccessRule rule) + public bool RemoveAccessRule(FileSystemAccessRule rule!!) { - if (rule == null) - throw new ArgumentNullException(nameof(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 @@ -206,11 +203,8 @@ public void RemoveAccessRuleAll(FileSystemAccessRule rule) base.RemoveAccessRuleAll(rule); } - public void RemoveAccessRuleSpecific(FileSystemAccessRule rule) + public void RemoveAccessRuleSpecific(FileSystemAccessRule rule!!) { - if (rule == null) - throw new ArgumentNullException(nameof(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 be8aaa27069ccc..975ffd5c5c6413 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,13 +9,8 @@ public sealed partial class DriveInfo : ISerializable { private readonly string _name; - public DriveInfo(string driveName) + public DriveInfo(string driveName!!) { - if (driveName == null) - { - throw new ArgumentNullException(nameof(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 8ea51f94eaf6d7..fd9c2ce4fa6baf 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 @@ -95,8 +95,10 @@ public FileSystemWatcher(string path) public FileSystemWatcher(string path, string filter) { CheckPathValidity(path); + ArgumentNullException.ThrowIfNull(filter); + _directory = path; - Filter = filter ?? throw new ArgumentNullException(nameof(filter)); + Filter = filter; } /// @@ -368,11 +370,8 @@ protected override void Dispose(bool disposing) } } - private static void CheckPathValidity(string path) + private static void CheckPathValidity(string path!!) { - if (path == null) - throw new ArgumentNullException(nameof(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 4f904ebaa64b07..0d06fa01ee7206 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 @@ -85,11 +85,8 @@ 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 ca418218259790..e50ed951a6959f 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 @@ -83,11 +83,8 @@ 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 75e76c313bf8cd..59c58059a946f0 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,11 +80,8 @@ 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)); } @@ -97,11 +94,8 @@ 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) @@ -132,11 +126,8 @@ 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 792a5bbbffb8df..ca36eab898dd90 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,11 +130,8 @@ 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)); } @@ -147,11 +144,8 @@ 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 367c6213c25fe3..18726a8437ad4b 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,11 +130,8 @@ 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)); } @@ -147,11 +144,8 @@ 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 bb6360f00d5b84..48b9b6f8db8f96 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,11 +116,8 @@ public void Close() } } - public void DeleteFile(string file) + public void DeleteFile(string file!!) { - if (file == null) - throw new ArgumentNullException(nameof(file)); - EnsureStoreIsValid(); try @@ -134,33 +131,22 @@ public void DeleteFile(string file) } } - public bool FileExists(string path) + public bool FileExists(string path!!) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } - EnsureStoreIsValid(); return File.Exists(GetFullPath(path)); } - public bool DirectoryExists(string path) + public bool DirectoryExists(string path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - EnsureStoreIsValid(); return Directory.Exists(GetFullPath(path)); } - public void CreateDirectory(string dir) + public void CreateDirectory(string dir!!) { - if (dir == null) - throw new ArgumentNullException(nameof(dir)); - EnsureStoreIsValid(); string isPath = GetFullPath(dir); // Prepend IS root @@ -192,11 +178,8 @@ public void CreateDirectory(string dir) } } - public void DeleteDirectory(string dir) + public void DeleteDirectory(string dir!!) { - if (dir == null) - throw new ArgumentNullException(nameof(dir)); - EnsureStoreIsValid(); try @@ -216,11 +199,8 @@ 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!!) { - if (searchPattern == null) - throw new ArgumentNullException(nameof(searchPattern)); - EnsureStoreIsValid(); try @@ -241,11 +221,8 @@ 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!!) { - if (searchPattern == null) - throw new ArgumentNullException(nameof(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 f620e115aedb46..cfa037eeb2a9a4 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,11 +81,8 @@ 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) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - if ((path.Length == 0) || path.Equals(BackSlash)) throw new ArgumentException( SR.IsolatedStorage_Path); diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx b/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx index ce321bd41a358a..a6c978a3c4977a 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx +++ b/src/libraries/System.IO.MemoryMappedFiles/src/Resources/Strings.resx @@ -171,9 +171,6 @@ FileMode.Truncate is not permitted when creating new memory mapped files. - - fileStream cannot be null. - The capacity cannot be greater than the size of the system's logical address space. 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 eb8dea4896635a..1b9e7217e96463 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,14 +103,9 @@ 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) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } - if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); @@ -189,15 +184,10 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string 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) { - if (fileStream == null) - { - throw new ArgumentNullException(nameof(fileStream), SR.ArgumentNull_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 12da788ace902c..e9178d5aefeb71 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,11 +70,8 @@ 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 == 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 475596098c1be2..6901cb11751c3a 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,11 +17,8 @@ internal sealed class IgnoreFlushAndCloseStream : Stream /// Constructor /// /// - internal IgnoreFlushAndCloseStream(Stream stream) + internal IgnoreFlushAndCloseStream(Stream stream!!) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - _stream = stream; } 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 4713d8f3497aaa..6b034018d4d814 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 @@ -383,14 +383,8 @@ private void ProcessEndElementForRelationshipTag(XmlCompatibilityReader reader) /// 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 == null) - throw new ArgumentNullException(nameof(targetUri)); - - if (relationshipType == 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/Package.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/Package.cs index 09c9b5c307534d..82b10256af998d 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,15 +823,11 @@ 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) { - Package? package = null; - if (path == null) - throw new ArgumentNullException(nameof(path)); - ThrowIfFileModeInvalid(packageMode); ThrowIfFileAccessInvalid(packageAccess); @@ -854,6 +850,7 @@ public static Package Open( //Verify if this is valid for filenames FileInfo packageFileInfo = new FileInfo(path); + Package? package = null; try { package = new ZipPackage(packageFileInfo.FullName, packageMode, packageAccess, packageShare); @@ -870,10 +867,7 @@ public static Package Open( } catch { - if (package != null) - { - package.Close(); - } + package?.Close(); throw; } @@ -891,12 +885,9 @@ 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) { Package? package = null; - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - try { // Today the Open(Stream) method is purely used for streams of Zip file format as @@ -915,10 +906,7 @@ public static Package Open(Stream stream, FileMode packageMode, FileAccess packa } catch { - if (package != null) - { - package.Close(); - } + package?.Close(); throw; } 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 c4a991056dcee5..becc0278706ef8 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,17 +93,11 @@ 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 == null) - throw new ArgumentNullException(nameof(package)); - - if (partUri == 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 d7376bc0615553..36aa72cb50c5c5 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,21 +110,10 @@ 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!!) { //sourcePart can be null to represent that the relationships are at the package level - if (package == null) - throw new ArgumentNullException(nameof(package)); - - if (targetUri == null) - throw new ArgumentNullException(nameof(targetUri)); - - if (relationshipType == null) - throw new ArgumentNullException(nameof(relationshipType)); - - if (id == null) - throw new ArgumentNullException(nameof(id)); // The ID is guaranteed to be an XML ID by the caller (InternalRelationshipCollection). // The following check is a precaution against future bug introductions. #if DEBUG 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 d594bff1cf4700..2ea435a5132ac3 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,14 +28,8 @@ 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 == null) - throw new ArgumentNullException(nameof(sourceUri)); - - if (selectionCriteria == 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); @@ -109,13 +103,8 @@ 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 == 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 5c1beb95c6b9a6..6222a5b00c768a 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,13 +163,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(destination)); - } - if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); @@ -185,13 +180,8 @@ public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancel /// 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 == null) - { - throw new ArgumentNullException(nameof(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 3dc9b49e3e1d5e..c1d4635b10cdbc 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,13 +45,8 @@ 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) - { - throw new ArgumentNullException(nameof(buffer)); - } - return ReadInternal(new Span(buffer, offset, count)); } @@ -80,13 +75,8 @@ 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) - { - throw new ArgumentNullException(nameof(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 22f764979bc629..9c5e19b05bbab9 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,13 +69,8 @@ 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) - { - throw new ArgumentNullException(nameof(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 75b2c26469966c..b9cecadcb9dba7 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,18 +14,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (destination == null) - { - throw new ArgumentNullException(nameof(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 cc457bf9bf2bff..288e7cb2fca019 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,15 +35,9 @@ 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!!) { - InnerStream = readingStream ?? throw new ArgumentNullException(nameof(readingStream)); - - if (options == null) - { - throw new ArgumentNullException(nameof(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 38de6ffad46b47..6e233f83d55d4b 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,15 +46,9 @@ private CancellationTokenSource InternalTokenSource } } - public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options) + public StreamPipeWriter(Stream writingStream!!, StreamPipeWriterOptions options!!) { - InnerStream = writingStream ?? throw new ArgumentNullException(nameof(writingStream)); - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - + InnerStream = writingStream; _minimumBufferSize = options.MinimumBufferSize; _pool = options.Pool == MemoryPool.Shared ? null : options.Pool; _maxPooledBufferSize = _pool?.MaxBufferSize ?? -1; diff --git a/src/libraries/System.IO.Pipes/src/Resources/Strings.resx b/src/libraries/System.IO.Pipes/src/Resources/Strings.resx index 166aacdb95798c..4d2752edab8b07 100644 --- a/src/libraries/System.IO.Pipes/src/Resources/Strings.resx +++ b/src/libraries/System.IO.Pipes/src/Resources/Strings.resx @@ -132,9 +132,6 @@ Handle has been disposed or is invalid. - - Buffer cannot be null. - serverName cannot be null. Use \".\" for current machine. diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs index 8c62382f50980e..b504db433bcb01 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs @@ -24,10 +24,7 @@ public AnonymousPipeClientStream(PipeDirection direction, string pipeHandleAsStr { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } - if (pipeHandleAsString == null) - { - throw new ArgumentNullException(nameof(pipeHandleAsString)); - } + ArgumentNullException.ThrowIfNull(pipeHandleAsString); // Initialize SafePipeHandle from String and check if it's valid. First see if it's parseable bool parseable = long.TryParse(pipeHandleAsString, out long result); @@ -53,10 +50,7 @@ public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePip { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } - if (safePipeHandle == null) - { - throw new ArgumentNullException(nameof(safePipeHandle)); - } + 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/AnonymousPipeServerStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs index bbebf3d79d993d..cdb54c60e37e9a 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeServerStream.cs @@ -37,14 +37,9 @@ public AnonymousPipeServerStream(PipeDirection direction, SafePipeHandle serverS { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } - if (serverSafePipeHandle == null) - { - throw new ArgumentNullException(nameof(serverSafePipeHandle)); - } - if (clientSafePipeHandle == null) - { - throw new ArgumentNullException(nameof(clientSafePipeHandle)); - } + ArgumentNullException.ThrowIfNull(serverSafePipeHandle); + ArgumentNullException.ThrowIfNull(clientSafePipeHandle); + if (serverSafePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(serverSafePipeHandle)); 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 a0240686342174..8a7a9213a76ffa 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,13 +87,9 @@ 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) { - if (safePipeHandle == null) - { - throw new ArgumentNullException(nameof(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 9fc1106e29282d..c9f46b24c54f90 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,13 +138,9 @@ 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) { - if (safePipeHandle == null) - { - throw new ArgumentNullException(nameof(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 c37f180e35df93..8d0b188b622631 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,37 +17,23 @@ public PipeSecurity() internal PipeSecurity(SafePipeHandle safeHandle, AccessControlSections includeSections) : base(false, ResourceType.KernelObject, safeHandle, includeSections) { } - public void AddAccessRule(PipeAccessRule rule) + public void AddAccessRule(PipeAccessRule rule!!) { - if (rule == null) - throw new ArgumentNullException(nameof(rule)); - base.AddAccessRule(rule); } - public void SetAccessRule(PipeAccessRule rule) + public void SetAccessRule(PipeAccessRule rule!!) { - if (rule == null) - throw new ArgumentNullException(nameof(rule)); - base.SetAccessRule(rule); } - public void ResetAccessRule(PipeAccessRule rule) + public void ResetAccessRule(PipeAccessRule rule!!) { - if (rule == null) - throw new ArgumentNullException(nameof(rule)); - base.ResetAccessRule(rule); } - public bool RemoveAccessRule(PipeAccessRule rule) + public bool RemoveAccessRule(PipeAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(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()); @@ -82,12 +68,8 @@ public bool RemoveAccessRule(PipeAccessRule rule) } } - public void RemoveAccessRuleSpecific(PipeAccessRule rule) + public void RemoveAccessRuleSpecific(PipeAccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(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 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 6ebcb91b312920..59bcc66559393f 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,13 +17,8 @@ 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!!) { - if (pipeSecurity == null) - { - throw new ArgumentNullException(nameof(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 dd490acaecf626..fd0a9b9c29bb42 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 @@ -566,14 +566,9 @@ private 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) { - if (portName == null) - { - throw new ArgumentNullException(nameof(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 2c9e86a8220750..73587fd40f7048 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,14 +555,9 @@ 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) { - if (portName == null) - { - throw new ArgumentNullException(nameof(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 2de7ab2d15b351..c197c3c8a52b5b 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,10 +88,8 @@ public override void Write(byte[] array, int offset, int count) Dispose(false); } - private void CheckArrayArguments(byte[] array, int offset, int count) + private void CheckArrayArguments(byte[] array!!, int offset, int count) { - if (array == null) - throw new ArgumentNullException(nameof(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/Runtime/CompilerServices/DynamicAttribute.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/DynamicAttribute.cs index db23e46dc13263..20803ebc1cc8bf 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,13 +42,8 @@ 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!!) { - if (transformFlags == null) - { - throw new ArgumentNullException(nameof(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 1524c49d9f08a9..4a571f1a69a0db 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,11 +46,8 @@ 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!!) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); - if (collection is ICollection c) { int count = c.Count; @@ -382,10 +379,8 @@ void IList.Remove(object? value) #region ICollection Members - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(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 0bb4d6990a9f5a..0602fd69596841 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/ParallelEnumerable.cs @@ -93,13 +93,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return new ParallelEnumerableWrapper(source); } @@ -118,13 +113,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return new PartitionerQueryOperator(source); } @@ -148,13 +138,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (!(source is ParallelEnumerableWrapper || source is IParallelPartitionable)) { if (source is PartitionerQueryOperator partitionerOp) @@ -191,13 +176,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - ParallelEnumerableWrapper? wrapper = source as ParallelEnumerableWrapper; if (wrapper == null) { @@ -220,13 +200,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - return new OrderingQueryOperator(QueryOperator.AsQueryOperator(source), false); } @@ -242,10 +217,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - return new ParallelEnumerableWrapper(source); } @@ -269,9 +242,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); // Ditch the wrapper, if there is one. if (source is ParallelEnumerableWrapper wrapper) @@ -301,9 +273,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); if (degreeOfParallelism < 1 || degreeOfParallelism > Scheduling.MAX_SUPPORTED_DOP) { throw new ArgumentOutOfRangeException(nameof(degreeOfParallelism)); @@ -330,10 +301,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - QuerySettings settings = QuerySettings.Empty; settings.CancellationState = new CancellationState(cancellationToken); @@ -358,9 +327,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); if (executionMode != ParallelExecutionMode.Default && executionMode != ParallelExecutionMode.ForceParallelism) { throw new ArgumentException(SR.ParallelEnumerable_WithQueryExecutionMode_InvalidMode); @@ -390,9 +358,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); if (mergeOptions != ParallelMergeOptions.Default && mergeOptions != ParallelMergeOptions.AutoBuffered && mergeOptions != ParallelMergeOptions.NotBuffered @@ -502,11 +469,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (action == null) throw new ArgumentNullException(nameof(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(); @@ -534,11 +498,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new WhereQueryOperator(source, predicate); } @@ -552,11 +513,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new IndexedWhereQueryOperator(source, predicate); } @@ -578,11 +536,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (selector == null) throw new ArgumentNullException(nameof(selector)); - return new SelectQueryOperator(source, selector); } @@ -599,11 +554,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (selector == null) throw new ArgumentNullException(nameof(selector)); - return new IndexedSelectQueryOperator(source, selector); } @@ -629,12 +581,8 @@ 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!!) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return new ZipQueryOperator(first, second, resultSelector); } @@ -750,16 +698,10 @@ 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) { - if (outer == null) throw new ArgumentNullException(nameof(outer)); - if (inner == null) throw new ArgumentNullException(nameof(inner)); - if (outerKeySelector == null) throw new ArgumentNullException(nameof(outerKeySelector)); - if (innerKeySelector == null) throw new ArgumentNullException(nameof(innerKeySelector)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return new JoinQueryOperator( outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } @@ -884,16 +826,10 @@ 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) { - if (outer == null) throw new ArgumentNullException(nameof(outer)); - if (inner == null) throw new ArgumentNullException(nameof(inner)); - if (outerKeySelector == null) throw new ArgumentNullException(nameof(outerKeySelector)); - if (innerKeySelector == null) throw new ArgumentNullException(nameof(innerKeySelector)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return new GroupJoinQueryOperator(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } @@ -949,11 +885,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (selector == null) throw new ArgumentNullException(nameof(selector)); - return new SelectManyQueryOperator(source, selector, null, null); } @@ -972,11 +905,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (selector == null) throw new ArgumentNullException(nameof(selector)); - return new SelectManyQueryOperator(source, null, selector, null); } @@ -1001,13 +931,9 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (collectionSelector == null) throw new ArgumentNullException(nameof(collectionSelector)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return new SelectManyQueryOperator(source, collectionSelector, null, resultSelector); } @@ -1037,13 +963,9 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (collectionSelector == null) throw new ArgumentNullException(nameof(collectionSelector)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return new SelectManyQueryOperator(source, null, collectionSelector, resultSelector); } @@ -1072,11 +994,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery( new SortQueryOperator(source, keySelector, null, false)); } @@ -1100,11 +1019,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery( new SortQueryOperator(source, keySelector, comparer, false)); } @@ -1127,11 +1043,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery(new SortQueryOperator(source, keySelector, null, true)); } @@ -1154,11 +1067,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery( new SortQueryOperator(source, keySelector, comparer, true)); } @@ -1184,11 +1094,8 @@ public static OrderedParallelQuery OrderByDescending( /// public static OrderedParallelQuery ThenBy( - this OrderedParallelQuery source, Func keySelector) + this OrderedParallelQuery source!!, Func keySelector!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, null, false)); } @@ -1215,11 +1122,8 @@ public static OrderedParallelQuery ThenBy( /// public static OrderedParallelQuery ThenBy( - this OrderedParallelQuery source, Func keySelector, IComparer? comparer) + this OrderedParallelQuery source!!, Func keySelector!!, IComparer? comparer) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, comparer, false)); } @@ -1245,11 +1149,8 @@ public static OrderedParallelQuery ThenBy( /// public static OrderedParallelQuery ThenByDescending( - this OrderedParallelQuery source, Func keySelector) + this OrderedParallelQuery source!!, Func keySelector!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, null, true)); } @@ -1276,10 +1177,8 @@ public static OrderedParallelQuery ThenByDescending( /// public static OrderedParallelQuery ThenByDescending( - this OrderedParallelQuery source, Func keySelector, IComparer? comparer) + this OrderedParallelQuery source!!, Func keySelector!!, IComparer? comparer) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return new OrderedParallelQuery( (QueryOperator)source.OrderedEnumerable.CreateOrderedEnumerable(keySelector, comparer, true)); } @@ -1322,11 +1221,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - return new GroupByQueryOperator(source, keySelector, null, comparer); } @@ -1375,12 +1271,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - if (elementSelector == null) throw new ArgumentNullException(nameof(elementSelector)); - return new GroupByQueryOperator(source, keySelector, elementSelector, comparer); } @@ -1414,11 +1306,9 @@ 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!!) { - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return source.GroupBy(keySelector) .Select, TResult>(delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1442,10 +1332,8 @@ 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) { - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return source.GroupBy(keySelector, comparer).Select, TResult>( delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1472,10 +1360,8 @@ 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!!) { - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return source.GroupBy(keySelector, elementSelector) .Select, TResult>(delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1503,10 +1389,8 @@ 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) { - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return source.GroupBy(keySelector, elementSelector, comparer) .Select, TResult>(delegate (IGrouping grouping) { return resultSelector(grouping.Key, grouping); }); } @@ -1624,10 +1508,8 @@ public static TSource Aggregate( } internal static TSource Aggregate( - this ParallelQuery source, Func func, QueryAggregationOptions options) + this ParallelQuery source!!, Func func!!, QueryAggregationOptions options) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (func == null) throw new ArgumentNullException(nameof(func)); if ((~(QueryAggregationOptions.Associative | QueryAggregationOptions.Commutative) & options) != 0) throw new ArgumentOutOfRangeException(nameof(options)); if ((options & QueryAggregationOptions.Associative) != QueryAggregationOptions.Associative) @@ -1671,10 +1553,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (func == null) throw new ArgumentNullException(nameof(func)); if ((~(QueryAggregationOptions.Associative | QueryAggregationOptions.Commutative) & options) != 0) throw new ArgumentOutOfRangeException(nameof(options)); return source.PerformSequentialAggregation(seed, true, func); @@ -1704,13 +1584,9 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (func == null) throw new ArgumentNullException(nameof(func)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - TAccumulate acc = source.PerformSequentialAggregation(seed, true, func); try { @@ -1760,14 +1636,9 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (updateAccumulatorFunc == null) throw new ArgumentNullException(nameof(updateAccumulatorFunc)); - if (combineAccumulatorsFunc == null) throw new ArgumentNullException(nameof(combineAccumulatorsFunc)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - return new AssociativeAggregationOperator( source, seed, null, true, updateAccumulatorFunc, combineAccumulatorsFunc, resultSelector, false, QueryAggregationOptions.AssociativeCommutative).Aggregate(); @@ -1813,18 +1684,12 @@ public static TResult Aggregate( /// The query was canceled. /// public static TResult Aggregate( - this ParallelQuery source, - Func seedFactory, - Func updateAccumulatorFunc, - Func combineAccumulatorsFunc, - Func resultSelector) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (seedFactory == null) throw new ArgumentNullException(nameof(seedFactory)); - if (updateAccumulatorFunc == null) throw new ArgumentNullException(nameof(updateAccumulatorFunc)); - if (combineAccumulatorsFunc == null) throw new ArgumentNullException(nameof(combineAccumulatorsFunc)); - if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); - + this ParallelQuery source!!, + Func seedFactory!!, + Func updateAccumulatorFunc!!, + Func combineAccumulatorsFunc!!, + Func resultSelector!!) + { return new AssociativeAggregationOperator( source, default!, seedFactory, true, updateAccumulatorFunc, combineAccumulatorsFunc, resultSelector, false, QueryAggregationOptions.AssociativeCommutative).Aggregate(); @@ -1852,10 +1717,8 @@ public static TResult Aggregate( /// /// The query was canceled. /// - public static int Count(this ParallelQuery source) + public static int Count(this ParallelQuery source!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - // If the data source is a collection, we can just return the count right away. if (source is ParallelEnumerableWrapper sourceAsWrapper) { @@ -1894,11 +1757,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - // Construct a where operator to filter out non-matching elements, and then aggregate. checked { @@ -1923,10 +1783,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - // If the data source is a collection, we can just return the count right away. if (source is ParallelEnumerableWrapper sourceAsWrapper) { @@ -1961,11 +1819,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - // Construct a where operator to filter out non-matching elements, and then aggregate. return new LongCountAggregationOperator(Where(source, predicate)).Aggregate(); } @@ -1990,9 +1845,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new IntSumAggregationOperator(source).Aggregate(); } @@ -2012,9 +1866,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableIntSumAggregationOperator(source).Aggregate(); } @@ -2034,9 +1887,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new LongSumAggregationOperator(source).Aggregate(); } @@ -2056,9 +1908,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableLongSumAggregationOperator(source).Aggregate(); } @@ -2076,9 +1927,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new FloatSumAggregationOperator(source).Aggregate(); } @@ -2096,9 +1946,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableFloatSumAggregationOperator(source).Aggregate(); } @@ -2116,9 +1965,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DoubleSumAggregationOperator(source).Aggregate(); } @@ -2136,9 +1984,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDoubleSumAggregationOperator(source).Aggregate(); } @@ -2158,9 +2005,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DecimalSumAggregationOperator(source).Aggregate(); } @@ -2180,9 +2026,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDecimalSumAggregationOperator(source).Aggregate(); } @@ -2448,9 +2293,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new IntMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2468,9 +2312,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableIntMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2491,9 +2334,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new LongMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2511,9 +2353,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableLongMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2534,9 +2375,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new FloatMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2554,9 +2394,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableFloatMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2577,9 +2416,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DoubleMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2597,9 +2435,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDoubleMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2620,9 +2457,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DecimalMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2640,9 +2476,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDecimalMinMaxAggregationOperator(source, -1).Aggregate(); } @@ -2664,9 +2499,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return AggregationMinMaxHelpers.ReduceMin(source); } @@ -2952,9 +2786,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new IntMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2972,9 +2805,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableIntMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -2995,9 +2827,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new LongMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3015,9 +2846,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableLongMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3038,9 +2868,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new FloatMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3058,9 +2887,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableFloatMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3081,9 +2909,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DoubleMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3101,9 +2928,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDoubleMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3124,9 +2950,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DecimalMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3144,9 +2969,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDecimalMinMaxAggregationOperator(source, 1).Aggregate(); } @@ -3167,9 +2991,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return AggregationMinMaxHelpers.ReduceMax(source); } @@ -3457,9 +3280,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new IntAverageAggregationOperator(source).Aggregate(); } @@ -3479,9 +3301,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableIntAverageAggregationOperator(source).Aggregate(); } @@ -3504,9 +3325,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new LongAverageAggregationOperator(source).Aggregate(); } @@ -3526,9 +3346,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableLongAverageAggregationOperator(source).Aggregate(); } @@ -3549,9 +3368,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new FloatAverageAggregationOperator(source).Aggregate(); } @@ -3569,9 +3387,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableFloatAverageAggregationOperator(source).Aggregate(); } @@ -3592,9 +3409,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DoubleAverageAggregationOperator(source).Aggregate(); } @@ -3612,9 +3428,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDoubleAverageAggregationOperator(source).Aggregate(); } @@ -3635,9 +3450,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DecimalAverageAggregationOperator(source).Aggregate(); } @@ -3655,9 +3469,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new NullableDecimalAverageAggregationOperator(source).Aggregate(); } @@ -3926,11 +3739,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new AnyAllSearchOperator(source, true, predicate).Aggregate(); } @@ -3949,10 +3759,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - return Any(source, x => true); } @@ -3978,11 +3786,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new AnyAllSearchOperator(source, false, predicate).Aggregate(); } @@ -4034,10 +3839,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - // @PERF: there are many simple optimizations we can make for collection types with known sizes. return new ContainsSearchOperator(source, value, comparer).Aggregate(); @@ -4063,10 +3866,8 @@ public static bool Contains(this ParallelQuery source, TSource /// /// 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (count > 0) { return new TakeOrSkipQueryOperator(source, count, true); @@ -4095,11 +3896,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new TakeOrSkipWhileQueryOperator(source, predicate, null, true); } @@ -4120,11 +3918,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new TakeOrSkipWhileQueryOperator(source, null, predicate, true); } @@ -4145,10 +3940,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - // If the count is 0 (or less) we just return the whole stream. if (count <= 0) { @@ -4177,11 +3970,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new TakeOrSkipWhileQueryOperator(source, predicate, null, false); } @@ -4204,11 +3994,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return new TakeOrSkipWhileQueryOperator(source, null, predicate, false); } @@ -4230,10 +4017,8 @@ 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!!) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); return new ConcatQueryOperator(first, second); } @@ -4282,10 +4067,8 @@ 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!!) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); return SequenceEqual(first, second, null); } @@ -4331,13 +4114,10 @@ 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) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); - // If comparer is null, use the default one - comparer = comparer ?? EqualityComparer.Default; + comparer ??= EqualityComparer.Default; QueryOperator leftOp = QueryOperator.AsQueryOperator(first); QueryOperator rightOp = QueryOperator.AsQueryOperator(second); @@ -4449,10 +4229,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - return new DistinctQueryOperator(source, comparer); } @@ -4510,11 +4288,8 @@ 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) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); - return new UnionQueryOperator(first, second, comparer); } @@ -4605,11 +4380,8 @@ 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) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); - return new IntersectQueryOperator(first, second, comparer); } @@ -4701,11 +4473,8 @@ 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) { - if (first == null) throw new ArgumentNullException(nameof(first)); - if (second == null) throw new ArgumentNullException(nameof(second)); - return new ExceptQueryOperator(first, second, comparer); } @@ -4776,10 +4545,8 @@ public static IEnumerable AsEnumerable(this ParallelQuery /// The query was canceled. /// - public static TSource[] ToArray(this ParallelQuery source) + public static TSource[] ToArray(this ParallelQuery source!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (source is QueryOperator asOperator) { return asOperator.ExecuteAndGetResultsAsArray(); @@ -4808,10 +4575,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - // Allocate a growable list (optionally passing the length as the initial size). List list = new List(); IEnumerator input; @@ -4919,11 +4684,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary result = new Dictionary(comparer); @@ -5016,12 +4778,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - if (elementSelector == null) throw new ArgumentNullException(nameof(elementSelector)); - // comparer may be null. In that case, the Dictionary constructor will use the default comparer. Dictionary result = new Dictionary(comparer); @@ -5098,11 +4856,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - // comparer may be null, in which case we use the default comparer. comparer = comparer ?? EqualityComparer.Default; @@ -5184,12 +4939,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); - if (elementSelector == null) throw new ArgumentNullException(nameof(elementSelector)); - // comparer may be null, in which case we use the default comparer. comparer = comparer ?? EqualityComparer.Default; @@ -5230,9 +4981,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new ReverseQueryOperator(source); } @@ -5251,10 +5001,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - return source.OfType(); } @@ -5269,10 +5017,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - return source.Cast(); } @@ -5354,12 +5100,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!!) { // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the 0th element. - if (source == null) throw new ArgumentNullException(nameof(source)); - FirstQueryOperator queryOp = new FirstQueryOperator(source, null); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5397,11 +5141,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - FirstQueryOperator queryOp = new FirstQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5436,10 +5177,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(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); @@ -5482,11 +5221,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - FirstQueryOperator queryOp = new FirstQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5530,12 +5266,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!!) { // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the last element. - if (source == null) throw new ArgumentNullException(nameof(source)); - LastQueryOperator queryOp = new LastQueryOperator(source, null); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5573,11 +5307,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - LastQueryOperator queryOp = new LastQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5614,12 +5345,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!!) { // @PERF: optimize for seekable data sources. E.g. if an array, we can // seek directly to the last element. - if (source == null) throw new ArgumentNullException(nameof(source)); - LastQueryOperator queryOp = new LastQueryOperator(source, null); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5656,11 +5385,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - LastQueryOperator queryOp = new LastQueryOperator(source, predicate); // If in conservative mode and a premature merge would be inserted by the First operator, @@ -5704,12 +5430,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!!) { // @PERF: optimize for ICollection-typed data sources, i.e. we can just // check the Count property and avoid costly fork/join/synchronization. - if (source == null) throw new ArgumentNullException(nameof(source)); - return GetOneWithPossibleDefault(new SingleQueryOperator(source, null), true, false)!; } @@ -5733,11 +5457,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return GetOneWithPossibleDefault(new SingleQueryOperator(source, predicate), true, false)!; } @@ -5760,12 +5481,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!!) { // @PERF: optimize for ICollection-typed data sources, i.e. we can just // check the Count property and avoid costly fork/join/synchronization. - if (source == null) throw new ArgumentNullException(nameof(source)); - return GetOneWithPossibleDefault(new SingleQueryOperator(source, null), true, true); } @@ -5790,11 +5509,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (predicate == null) throw new ArgumentNullException(nameof(predicate)); - return GetOneWithPossibleDefault(new SingleQueryOperator(source, predicate), true, true); } @@ -5833,9 +5549,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); return new DefaultIfEmptyQueryOperator(source, defaultValue); } @@ -5864,9 +5579,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); // @PERF: there are obvious optimization opportunities for indexable data sources, @@ -5903,10 +5617,8 @@ public static TSource ElementAt(this ParallelQuery source, int /// /// The query was canceled. /// - public static TSource? ElementAtOrDefault(this ParallelQuery source, int index) + public static TSource? ElementAtOrDefault(this ParallelQuery source!!, int index) { - if (source == null) throw new ArgumentNullException(nameof(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.Memory.Data/src/System/BinaryData.cs b/src/libraries/System.Memory.Data/src/System/BinaryData.cs index b13232f49f0ff1..889c303df445bf 100644 --- a/src/libraries/System.Memory.Data/src/System/BinaryData.cs +++ b/src/libraries/System.Memory.Data/src/System/BinaryData.cs @@ -33,9 +33,9 @@ public class BinaryData /// provided byte array. /// /// The array to wrap. - public BinaryData(byte[] data) + public BinaryData(byte[] data!!) { - _bytes = data ?? throw new ArgumentNullException(nameof(data)); + _bytes = data; } /// @@ -70,13 +70,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(data)); - } - _bytes = Encoding.UTF8.GetBytes(data); } @@ -110,13 +105,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(stream)); - } - return FromStreamAsync(stream, async: false).GetAwaiter().GetResult(); } @@ -127,13 +117,8 @@ 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 == 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 11ec18302bd03b..72bbd7af7da6ac 100644 --- a/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs +++ b/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs @@ -31,18 +31,8 @@ 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!!) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } - if (chars.Length <= MaxInputElementsPerIteration) { // The input span is small enough where we can one-shot this. @@ -74,17 +64,8 @@ public static long GetBytes(this Encoding encoding, ReadOnlySpan chars, IB /// 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!!) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } // Delegate to the Span-based method if possible. // If that doesn't work, allocate the Encoder instance and run a loop. @@ -111,13 +92,8 @@ public static long GetBytes(this Encoding encoding, in ReadOnlySequence ch /// 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) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - if (chars.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -156,13 +132,8 @@ public static int GetBytes(this Encoding encoding, in ReadOnlySequence cha /// 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) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - if (chars.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -242,18 +213,8 @@ public static byte[] GetBytes(this Encoding encoding, in ReadOnlySequence /// 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, ReadOnlySpan bytes, IBufferWriter writer) + public static long GetChars(this Encoding encoding!!, ReadOnlySpan bytes, IBufferWriter writer!!) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } - if (bytes.Length <= MaxInputElementsPerIteration) { // The input span is small enough where we can one-shot this. @@ -285,18 +246,8 @@ public static long GetChars(this Encoding encoding, ReadOnlySpan bytes, IB /// 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!!) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } - // Delegate to the Span-based method if possible. // If that doesn't work, allocate the Encoder instance and run a loop. @@ -322,13 +273,8 @@ public static long GetChars(this Encoding encoding, in ReadOnlySequence by /// 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) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - if (bytes.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -367,13 +313,8 @@ public static int GetChars(this Encoding encoding, in ReadOnlySequence byt /// 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) { - if (encoding is null) - { - throw new ArgumentNullException(nameof(encoding)); - } - if (bytes.IsSingleSegment) { // If the incoming sequence is single-segment, one-shot this. @@ -451,18 +392,8 @@ 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) { - if (encoder is null) - { - throw new ArgumentNullException(nameof(encoder)); - } - - if (writer is null) - { - throw new ArgumentNullException(nameof(writer)); - } - // We need to perform at least one iteration of the loop since the encoder could have internal state. long totalBytesWritten = 0; @@ -544,18 +475,8 @@ 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) { - if (decoder is null) - { - throw new ArgumentNullException(nameof(decoder)); - } - - if (writer is null) - { - throw new ArgumentNullException(nameof(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 66924779bc73d5..9ec475fdda12e1 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,93 +16,53 @@ namespace System.Net.Http.Json public static partial class HttpClientJsonExtensions { [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task GetFromJsonAsync(this HttpClient client, string? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client!!, string? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (client == 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 == 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, string? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client!!, string? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) { - if (client == 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 == 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, string? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client!!, string? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { - if (client == 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 == 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, string? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task GetFromJsonAsync(this HttpClient client!!, string? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client == 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 == 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 f11f81d068d480..93e9e91180ae7b 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 @@ -23,13 +23,8 @@ 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, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PatchAsJsonAsync(this HttpClient client!!, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } - JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PatchAsync(requestUri, content, cancellationToken); } @@ -46,13 +41,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(client)); - } - JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PatchAsync(requestUri, content, cancellationToken); } @@ -96,13 +86,8 @@ 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, string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PatchAsJsonAsync(this HttpClient client!!, string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } - JsonContent content = new(value, jsonTypeInfo); return client.PatchAsync(requestUri, content, cancellationToken); } @@ -118,13 +103,8 @@ 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 == 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 2ddbd37fc5af09..56514706d516a5 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,25 +12,15 @@ namespace System.Net.Http.Json public static partial class HttpClientJsonExtensions { [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PostAsJsonAsync(this HttpClient client, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PostAsJsonAsync(this HttpClient client!!, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == 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 == null) - { - throw new ArgumentNullException(nameof(client)); - } - JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PostAsync(requestUri, content, cancellationToken); } @@ -43,24 +33,14 @@ 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, string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PostAsJsonAsync(this HttpClient client!!, string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client == 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 == 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 6ddac02298f096..9f362999af3136 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,25 +12,15 @@ namespace System.Net.Http.Json public static partial class HttpClientJsonExtensions { [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] - public static Task PutAsJsonAsync(this HttpClient client, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) + public static Task PutAsJsonAsync(this HttpClient client!!, string? requestUri, TValue value, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (client == 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 == null) - { - throw new ArgumentNullException(nameof(client)); - } - JsonContent content = JsonContent.Create(value, mediaType: null, options); return client.PutAsync(requestUri, content, cancellationToken); } @@ -43,24 +33,14 @@ 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, string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) + public static Task PutAsJsonAsync(this HttpClient client!!, string? requestUri, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { - if (client == 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 == 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 ac771c9d158697..8f2d951f9c39ae 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,26 +17,16 @@ 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 == 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 == null) - { - throw new ArgumentNullException(nameof(content)); - } - Encoding? sourceEncoding = JsonHelpers.GetEncoding(content.Headers.ContentType?.CharSet); return ReadFromJsonAsyncCore(content, sourceEncoding, options, cancellationToken); @@ -74,25 +64,15 @@ 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 == 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 == 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 f1430c31ea58d5..f9a620e0db7334 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,15 +23,10 @@ public sealed partial class JsonContent : HttpContent [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] private JsonContent( object? inputValue, - Type inputType, + Type inputType!!, MediaTypeHeaderValue? mediaType, JsonSerializerOptions? options) { - if (inputType == 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 a676e425c43dde..d5ac1fca28d2d8 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 @@ -19,9 +19,9 @@ internal sealed partial class JsonContent : HttpContent private readonly TValue _typedValue; - public JsonContent(TValue inputValue, JsonTypeInfo jsonTypeInfo) + public JsonContent(TValue inputValue, JsonTypeInfo jsonTypeInfo!!) { - _typeInfo = jsonTypeInfo ?? 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 976b40250a6c38..c46d1cce0f43c0 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,13 +67,8 @@ 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 == 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 2217baefb6ea40..1cc8bab3e48b26 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,13 +66,8 @@ 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 == 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 a081b7b4d00459..d6c46b18cc1476 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,14 +568,9 @@ protected override void Dispose(bool disposing) } protected override Task SendAsync( - HttpRequestMessage request, + HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - 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 5e79072f44ba8b..68794b69b666e1 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,13 +97,8 @@ 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 == 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 74f0abbbb8050c..5670b305fa408f 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,13 +172,8 @@ 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 == 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 b03247fbfc3d7e..1b4ac0fce85967 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 @@ -142,12 +142,8 @@ protected internal override HttpResponseMessage Send(HttpRequestMessage request, throw new PlatformNotSupportedException(); } - protected internal override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected internal override async Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } CancellationTokenRegistration? abortRegistration = null; try { @@ -352,10 +348,10 @@ 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) { - _fetchResponse = fetchResponse ?? throw new ArgumentNullException(nameof(fetchResponse)); - _abortController = abortController ?? throw new ArgumentNullException(nameof(abortController)); + _fetchResponse = fetchResponse; + _abortController = abortController; _abortRegistration = abortRegistration; } @@ -396,9 +392,9 @@ private sealed class BrowserHttpContent : HttpContent private byte[]? _data; private readonly WasmFetchResponse _status; - public BrowserHttpContent(WasmFetchResponse status) + public BrowserHttpContent(WasmFetchResponse status!!) { - _status = status ?? throw new ArgumentNullException(nameof(status)); + _status = status; } private async Task GetResponseData(CancellationToken cancellationToken) 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 fd9e91ad4f4cba..92742ea64afbc5 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,23 +14,14 @@ public class ByteArrayContent : HttpContent private readonly int _offset; private readonly int _count; - public ByteArrayContent(byte[] content) + public ByteArrayContent(byte[] content!!) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - _content = content; _count = content.Length; } - public ByteArrayContent(byte[] content, int offset, int count) + public ByteArrayContent(byte[] content!!, int offset, int count) { - if (content == null) - { - throw new ArgumentNullException(nameof(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 ebc61f3922392c..c21c4d4db10d39 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 @@ -25,10 +25,7 @@ public HttpMessageHandler? InnerHandler } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); CheckDisposedOrStarted(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, value); @@ -45,22 +42,14 @@ protected DelegatingHandler(HttpMessageHandler innerHandler) InnerHandler = innerHandler; } - protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) + protected internal override HttpResponseMessage Send(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } SetOperationStarted(); return _innerHandler!.Send(request, cancellationToken); } - protected internal override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected internal override Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } 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 253f82e5594a24..7c208012eaf18f 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 @@ -88,7 +88,7 @@ internal override ValueTask SendAsync(HttpRequestMessage re } } - private async ValueTask SendAsyncCore(HttpRequestMessage request, bool async, + private async ValueTask SendAsyncCore(HttpRequestMessage request!!, bool async, CancellationToken cancellationToken) { // HttpClientHandler is responsible to call static DiagnosticsHandler.IsEnabled() before forwarding request here. @@ -97,11 +97,6 @@ private async ValueTask SendAsyncCore(HttpRequestMessage re // So some requests happening right after subscription starts might not be instrumented. Similarly, // when consumer unsubscribes, extra requests might be instrumented - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - // Since we are reusing the request message instance on redirects, clear any existing headers // Do so before writing DiagnosticListener events as instrumentations use those to inject headers if (request.WasRedirected() && _propagatorFields is HeaderDescriptor[] fields) 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 abf61ca7ee0516..43f5102201e7b4 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,13 +23,8 @@ public FormUrlEncodedContent( Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); } - private static byte[] GetContentByteArray(IEnumerable> nameValueCollection) + private static byte[] GetContentByteArray(IEnumerable> nameValueCollection!!) { - if (nameValueCollection == null) - { - throw new ArgumentNullException(nameof(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 97c458a6d6b855..7ae54578ed03db 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,12 +78,8 @@ public bool Contains(T item) return _store.ContainsParsedValue(_descriptor, item); } - public void CopyTo(T[] array, int arrayIndex) + public void CopyTo(T[] array!!, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } // Allow arrayIndex == array.Length in case our own collection is empty if ((arrayIndex < 0) || (arrayIndex > array.Length)) { @@ -166,13 +162,8 @@ public override string ToString() return _store.GetHeaderString(_descriptor); } - private void CheckValue(T item) + private void CheckValue(T item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(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 266d471001835b..db68c4478bbfbf 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 @@ -94,13 +94,8 @@ 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!!) { - if (values == null) - { - throw new ArgumentNullException(nameof(values)); - } - PrepareHeaderInfoForAdd(descriptor, out HeaderStoreItemInfo info, out bool addToStore); try @@ -165,13 +160,8 @@ 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!!) { - if (values == null) - { - throw new ArgumentNullException(nameof(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 3799eba085b148..0c116e160471c8 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,12 +9,8 @@ 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!!) { - if (item is null) - { - throw new ArgumentNullException(nameof(item)); - } } } 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 4c69dec3e80835..773d8658767a2b 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,13 +26,8 @@ public ProductInfoHeaderValue(string productName, string? productVersion) { } - public ProductInfoHeaderValue(ProductHeaderValue product) + public ProductInfoHeaderValue(ProductHeaderValue product!!) { - if (product == null) - { - throw new ArgumentNullException(nameof(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 65677caac1d6d9..97e3a591cc2a87 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,13 +26,8 @@ public RangeConditionHeaderValue(DateTimeOffset date) _date = date; } - public RangeConditionHeaderValue(EntityTagHeaderValue entityTag) + public RangeConditionHeaderValue(EntityTagHeaderValue entityTag!!) { - if (entityTag == null) - { - throw new ArgumentNullException(nameof(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 3b77aeafc0467b..adc4fea4448a4a 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 @@ -553,13 +553,8 @@ async Task Core( } } - private void CheckRequestBeforeSend(HttpRequestMessage request) + private void CheckRequestBeforeSend(HttpRequestMessage request!!) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - CheckDisposed(); CheckRequestMessage(request); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs index 2284b33b80a719..53ae907c7bfe7f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs @@ -116,10 +116,7 @@ public CookieContainer CookieContainer } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (IsNativeHandlerEnabled) { @@ -792,4 +789,4 @@ private object InvokeNativeHandlerMethod(string name, params object?[] parameter "System.Net.Http.UseNativeHttpHandler", false); } -} \ No newline at end of file +} diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs index 1f11fbf9f6f735..623a7f02efe224 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs @@ -76,10 +76,7 @@ public CookieContainer CookieContainer get => _underlyingHandler.CookieContainer; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _underlyingHandler.CookieContainer = value; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs index 5c907ad6150b7a..9b1b9445a6deb6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs @@ -361,11 +361,7 @@ protected virtual Task SerializeToStreamAsync(Stream stream, TransportContext? c public void CopyTo(Stream stream, TransportContext? context, CancellationToken cancellationToken) { CheckDisposed(); - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - + ArgumentNullException.ThrowIfNull(stream); try { if (TryGetBuffer(out ArraySegment buffer)) @@ -395,11 +391,7 @@ public Task CopyToAsync(Stream stream, TransportContext? context) => public Task CopyToAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { CheckDisposed(); - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - + ArgumentNullException.ThrowIfNull(stream); try { return WaitAsync(InternalCopyToAsync(stream, context, cancellationToken)); 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 9b33c75b4b22d4..643d0f110f555f 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,13 +20,8 @@ public HttpMessageInvoker(HttpMessageHandler handler) { } - public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler) + public HttpMessageInvoker(HttpMessageHandler handler!!, bool disposeHandler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } - if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, handler); _handler = handler; @@ -34,12 +29,8 @@ public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler) } [UnsupportedOSPlatformAttribute("browser")] - public virtual HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) + public virtual HttpResponseMessage Send(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } CheckDisposed(); if (ShouldSendWithTelemetry(request)) @@ -66,12 +57,8 @@ public virtual HttpResponseMessage Send(HttpRequestMessage request, Cancellation } } - public virtual Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + public virtual Task SendAsync(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(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 6c71b4c08633f1..3542cfc05d7449 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 @@ -35,10 +35,7 @@ public Version Version get { return _version; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); CheckDisposed(); _version = value; @@ -88,10 +85,7 @@ public HttpMethod Method get { return _method; } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); CheckDisposed(); _method = value; @@ -125,12 +119,12 @@ public HttpRequestMessage() { } - public HttpRequestMessage(HttpMethod method, Uri? requestUri) + public HttpRequestMessage(HttpMethod method!!, Uri? requestUri) { // 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. - _method = method ?? throw new ArgumentNullException(nameof(method)); + _method = method; _requestUri = requestUri; _version = DefaultRequestVersion; _versionPolicy = DefaultVersionPolicy; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs index 49f6a6f34a72ec..b968a7f966620f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs @@ -28,10 +28,7 @@ public Version Version set { #if !PHONE - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); #endif CheckDisposed(); 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 d0c3748d4943de..0d08eb6141115c 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,14 +27,9 @@ 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) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - // 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); @@ -42,14 +37,9 @@ 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) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - // 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 4ac7a34a126950..d9ed3613a1dca7 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,13 +108,8 @@ private static string GetDefaultBoundary() return Guid.NewGuid().ToString(); } - public virtual void Add(HttpContent content) + public virtual void Add(HttpContent content!!) { - if (content == null) - { - throw new ArgumentNullException(nameof(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 2ea780aa3a65fa..e4206d4d65ef54 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,27 +23,15 @@ public MultipartFormDataContent(string boundary) { } - public override void Add(HttpContent content) + public override void Add(HttpContent content!!) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - if (content.Headers.ContentDisposition == null) - { - content.Headers.ContentDisposition = new ContentDispositionHeaderValue(formData); - } + content.Headers.ContentDisposition ??= new ContentDispositionHeaderValue(formData); base.Add(content); } - public void Add(HttpContent content, string name) + public void Add(HttpContent content!!, string name) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(name)); @@ -52,12 +40,8 @@ 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) { - if (content == null) - { - throw new ArgumentNullException(nameof(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 72befb088edce5..17e9e7664658d6 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,14 +33,9 @@ private Stream ConsumeStream() return _stream; } - protected override void SerializeToStream(Stream stream, TransportContext? context, + protected override void SerializeToStream(Stream stream!!, TransportContext? context, CancellationToken cancellationToken) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - using (Stream contentStream = ConsumeStream()) { const int BufferSize = 8192; @@ -51,13 +46,8 @@ protected override void SerializeToStream(Stream stream, TransportContext? conte 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 async Task SerializeToStreamAsync(Stream stream!!, TransportContext? context, CancellationToken cancellationToken) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - using (Stream contentStream = ConsumeStream()) { const int BufferSize = 8192; 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 5be369967df859..9fc4bab05ff11f 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,14 +531,9 @@ private HttpMessageHandlerStage SetupHandlerChain() return _handler; } - protected internal override HttpResponseMessage Send(HttpRequestMessage request, + protected internal override HttpResponseMessage Send(HttpRequestMessage request!!, CancellationToken cancellationToken) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - if (request.Version.Major >= 2) { throw new NotSupportedException(SR.Format(SR.net_http_http2_sync_not_supported, GetType())); @@ -565,13 +560,8 @@ 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) { - if (request == null) - { - throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); - } - 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 12fab2a7807a87..6a33a01b17ee64 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,23 +17,14 @@ public class StreamContent : HttpContent private bool _contentConsumed; private long _start; - public StreamContent(Stream content) + public StreamContent(Stream content!!) { - if (content == null) - { - throw new ArgumentNullException(nameof(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) { - if (content == null) - { - throw new ArgumentNullException(nameof(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 05ec413dbdb533..da2fcf8d003aa3 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 @@ -36,19 +36,12 @@ public StringContent(string content, Encoding? encoding, string? mediaType) // 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) { // 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. - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - if (encoding == null) - { - encoding = HttpContent.DefaultStringEncoding; - } + encoding ??= HttpContent.DefaultStringEncoding; return encoding.GetBytes(content); } 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 adad957f1321cb..cee7d986e669e4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs @@ -59,10 +59,7 @@ public ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate set { CheckDisposed(); - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _extendedProtectionSelectorDelegate = value; } @@ -84,10 +81,7 @@ public ExtendedProtectionPolicy ExtendedProtectionPolicy set { CheckDisposed(); - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.CustomChannelBinding != null) { throw new ArgumentException(SR.net_listener_cannot_set_custom_cbt, nameof(value)); @@ -108,15 +102,11 @@ public HttpListenerPrefixCollection Prefixes } } - internal void AddPrefix(string uriPrefix) + internal void AddPrefix(string uriPrefix!!) { string? registeredPrefix; try { - if (uriPrefix == null) - { - throw new ArgumentNullException(nameof(uriPrefix)); - } CheckDisposed(); int i; if (string.Compare(uriPrefix, 0, "http://", 0, 7, StringComparison.OrdinalIgnoreCase) == 0) @@ -197,10 +187,7 @@ internal bool RemovePrefix(string uriPrefix) { CheckDisposed(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"uriPrefix: {uriPrefix}"); - if (uriPrefix == null) - { - throw new ArgumentNullException(nameof(uriPrefix)); - } + ArgumentNullException.ThrowIfNull(uriPrefix); if (!_uriPrefixes.Contains(uriPrefix)) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs index bcd9cc4beb547e..339036ec093324 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerPrefixCollection.cs @@ -38,10 +38,7 @@ internal HttpListenerPrefixCollection(HttpListener listener) public void CopyTo(Array array, int offset) { _httpListener.CheckDisposed(); - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (Count > array.Length) { throw new ArgumentOutOfRangeException(nameof(array), SR.net_array_too_small); @@ -60,10 +57,7 @@ public void CopyTo(Array array, int offset) public void CopyTo(string[] array, int offset) { _httpListener.CheckDisposed(); - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (Count > array.Length) { throw new ArgumentOutOfRangeException(nameof(array), SR.net_array_too_small); 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 1568b663337460..f7aa14bd8a20ce 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -175,10 +175,7 @@ public string StatusDescription set { CheckDisposed(); - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Need to verify the status description doesn't contain any control characters except HT. We mask off the high // byte since that's how it's encoded. @@ -207,12 +204,8 @@ public void AppendHeader(string name, string value) Headers.Add(name, value); } - public void AppendCookie(Cookie cookie) + public void AppendCookie(Cookie cookie!!) { - if (cookie == null) - { - throw new ArgumentNullException(nameof(cookie)); - } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"cookie: {cookie}"); Cookies.Add(cookie); } @@ -274,13 +267,8 @@ public void Redirect(string url) StatusDescription = HttpStatusDescription.Get(StatusCode)!; } - public void SetCookie(Cookie cookie) + public void SetCookie(Cookie cookie!!) { - if (cookie == null) - { - throw new ArgumentNullException(nameof(cookie)); - } - Cookie newCookie = cookie.Clone(); int added = Cookies.InternalAdd(newCookie, true); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs index f082d7cd944643..c0929c433606fb 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs @@ -67,10 +67,7 @@ public override void EndWrite(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult:{asyncResult}"); - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); EndWriteCore(asyncResult); } 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 40dbf3c94ceb46..be93b1248605da 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,11 +149,8 @@ private void OnRead(IAsyncResult base_ares) } } - public override int EndRead(IAsyncResult asyncResult) + public override int EndRead(IAsyncResult asyncResult!!) { - if (asyncResult == null) - throw new ArgumentNullException(nameof(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/HttpListener.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs index 3839b27cff25b4..a709cf3dffbc39 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs @@ -305,10 +305,7 @@ public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state) public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { CheckDisposed(); - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); ListenerAsyncResult? ares = asyncResult as ListenerAsyncResult; 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 558570b28cfbd0..79f5013d264a2e 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,11 +392,8 @@ private IAsyncResult BeginGetClientCertificateCore(AsyncCallback? requestCallbac return asyncResult; } - public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult!!) { - if (asyncResult == null) - throw new ArgumentNullException(nameof(asyncResult)); - GetClientCertificateAsyncResult? clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs index 2a8fc6efd38729..728e784c43816d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs @@ -64,10 +64,7 @@ public Version ProtocolVersion set { CheckDisposed(); - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1)) { throw new ArgumentException(SR.net_wrongversion, nameof(value)); @@ -119,10 +116,7 @@ public void Close(byte[] responseEntity, bool willBlock) { CheckDisposed(); - if (responseEntity == null) - { - throw new ArgumentNullException(nameof(responseEntity)); - } + ArgumentNullException.ThrowIfNull(responseEntity); if (!SentHeaders && _boundaryType != BoundaryType.Chunked) { 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 bdfb7f3f8c869e..ce6056af78a872 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,11 +161,8 @@ 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!!) { - if (asyncResult == null) - throw new ArgumentNullException(nameof(asyncResult)); - if (asyncResult is HttpStreamAsyncResult r) { if (!ReferenceEquals(this, r._parent)) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 5e2dedd9fd78fe..2be64de238d1d9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -659,10 +659,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) try { CheckDisposed(); - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult: {asyncResult}"); if (!(asyncResult is ListenerAsyncResult castedAsyncResult) || !(castedAsyncResult.AsyncObject is HttpListenerSession session) || session.Listener != this) { 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 0e21c34681fe8c..c48b34667ce527 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,14 +252,9 @@ internal void SetClientCertificateError(int clientCertificateError) _clientCertificateError = clientCertificateError; } - public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult!!) { X509Certificate2? clientCertificate = null; - - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs index 0c4b36af8efc75..35c4adde7144ce 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs @@ -82,10 +82,7 @@ public Version ProtocolVersion set { CheckDisposed(); - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1)) { throw new ArgumentException(SR.net_wrongversion, nameof(value)); @@ -121,10 +118,7 @@ public void Close() public void Close(byte[] responseEntity, bool willBlock) { CheckDisposed(); - if (responseEntity == null) - { - throw new ArgumentNullException(nameof(responseEntity)); - } + ArgumentNullException.ThrowIfNull(responseEntity); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"ResponseState:{_responseState}, BoundaryType:{_boundaryType}, ContentLength:{_contentLength}"); if (!SentHeaders && _boundaryType != BoundaryType.Chunked) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 214416962eba75..52167a955eefff 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -219,10 +219,7 @@ public override int EndRead(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"asyncResult: {asyncResult}"); - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); HttpRequestStreamAsyncResult? castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; if (castedAsyncResult == null || castedAsyncResult.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 9b9c501746de26..76da09f7976701 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,13 +162,8 @@ private static unsafe ulong SendWebSocketHeaders(HttpListenerResponse response) true); } - internal static void ValidateInnerStream(Stream innerStream) + internal static void ValidateInnerStream(Stream innerStream!!) { - if (innerStream == null) - { - throw new ArgumentNullException(nameof(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 5cc84a523deffc..eaeaecc6cc0401 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs @@ -156,23 +156,13 @@ 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!!) { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } - return ReadAsyncResult.End(asyncResult); } - public override void EndWrite(IAsyncResult asyncResult) + public override void EndWrite(IAsyncResult asyncResult!!) { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(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 d253ef78f36481..c5533daf552485 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs @@ -11,11 +11,8 @@ internal abstract class DelegatedStream : Stream { private readonly Stream _stream; - protected DelegatedStream(Stream stream) + protected DelegatedStream(Stream stream!!) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - _stream = stream; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/AlternateViewCollection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/AlternateViewCollection.cs index eae7b633d3969d..40f064e8794271 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/AlternateViewCollection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/AlternateViewCollection.cs @@ -45,24 +45,14 @@ protected override void ClearItems() protected override void SetItem(int index, AlternateView item) { ObjectDisposedException.ThrowIf(_disposed, this); - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - + ArgumentNullException.ThrowIfNull(item); base.SetItem(index, item); } protected override void InsertItem(int index, AlternateView item) { ObjectDisposedException.ThrowIf(_disposed, this); - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); } } 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 4fc0954e945210..a8c67d806ac942 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,17 +82,9 @@ 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) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - if (_part.Stream != null) - { - _part.Stream.Close(); - } + _part.Stream?.Close(); Encoding encoding; @@ -124,17 +116,9 @@ 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) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } - - if (_part.Stream != null) - { - _part.Stream.Close(); - } + _part.Stream?.Close(); if (string.IsNullOrEmpty(mediaType)) { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/AttachmentCollection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/AttachmentCollection.cs index 96be60c1fdcfb5..64c9d3c283c5cb 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/AttachmentCollection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/AttachmentCollection.cs @@ -45,24 +45,14 @@ protected override void ClearItems() protected override void SetItem(int index, Attachment item) { ObjectDisposedException.ThrowIf(_disposed, this); - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - + ArgumentNullException.ThrowIfNull(item); base.SetItem(index, item); } protected override void InsertItem(int index, Attachment item) { ObjectDisposedException.ThrowIf(_disposed, this); - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); } } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/LinkedResourceCollection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/LinkedResourceCollection.cs index c32b21197e91cf..5e76e927f2ba84 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/LinkedResourceCollection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/LinkedResourceCollection.cs @@ -44,24 +44,14 @@ protected override void ClearItems() protected override void SetItem(int index, LinkedResource item) { ObjectDisposedException.ThrowIf(_disposed, this); - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - + ArgumentNullException.ThrowIfNull(item); base.SetItem(index, item); } protected override void InsertItem(int index, LinkedResource item) { ObjectDisposedException.ThrowIf(_disposed, this); - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - + ArgumentNullException.ThrowIfNull(item); base.InsertItem(index, item); } } 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 41d3ba32a70219..d3ccf39ae51643 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,23 +23,13 @@ public void Add(string addresses) ParseValue(addresses); } - protected override void SetItem(int index, MailAddress item) + protected override void SetItem(int index, MailAddress item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - base.SetItem(index, item); } - protected override void InsertItem(int index, MailAddress item) + protected override void InsertItem(int index, MailAddress item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(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 dfa63b9641f7ca..cb4c835eb4556e 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,14 +52,8 @@ public MailMessage(string from, string to, string? subject, string? body) : this } - public MailMessage(MailAddress from, MailAddress to) + public MailMessage(MailAddress from!!, MailAddress to!!) { - if (from == null) - throw new ArgumentNullException(nameof(from)); - - if (to == null) - throw new ArgumentNullException(nameof(to)); - _message = new Message(from, to); } @@ -72,10 +66,7 @@ public MailAddress? From } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _message.From = value; } } 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 e6536a48e2b456..89544c98ebfd89 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 @@ -85,10 +85,7 @@ internal MailAddress? From } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _from = value; } } @@ -234,11 +231,7 @@ internal MimeBasePart? Content } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - + ArgumentNullException.ThrowIfNull(value); _content = value; } } @@ -303,13 +296,8 @@ internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allow } } - internal void EndSend(IAsyncResult asyncResult) + internal void EndSend(IAsyncResult asyncResult!!) { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(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 f41b6992e6563c..914087cee23f87 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,11 +22,8 @@ internal MailWriter(Stream stream, bool encodeForTransport) { } - internal override void WriteHeaders(NameValueCollection headers, bool allowUnicode) + internal override void WriteHeaders(NameValueCollection headers!!, bool allowUnicode) { - if (headers == null) - throw new ArgumentNullException(nameof(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 e9550139b62861..d9b82ea30390df 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,11 +18,8 @@ static SmtpAuthenticationManager() Register(new SmtpLoginAuthenticationModule()); } - internal static void Register(ISmtpAuthenticationModule module) + internal static void Register(ISmtpAuthenticationModule module!!) { - if (module == null) - throw new ArgumentNullException(nameof(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 71f0af271d14b2..769d973d397810 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,7 +413,7 @@ public void Send(string from, string recipients, string? subject, string? body) Send(mailMessage); } - public void Send(MailMessage message) + public void Send(MailMessage message!!) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -430,11 +430,6 @@ public void Send(MailMessage message) throw new InvalidOperationException(SR.net_inasync); } - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - if (DeliveryMethod == SmtpDeliveryMethod.Network) CheckHostAndPort(); @@ -563,7 +558,6 @@ public void SendAsync(MailMessage message, object? userToken) { ObjectDisposedException.ThrowIf(_disposed, this); - try { if (InCall) @@ -571,10 +565,7 @@ public void SendAsync(MailMessage message, object? userToken) throw new InvalidOperationException(SR.net_inasync); } - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } + ArgumentNullException.ThrowIfNull(message); if (DeliveryMethod == SmtpDeliveryMethod.Network) CheckHostAndPort(); 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 8307087837400f..a9f115a72e1e9c 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,28 +34,17 @@ protected SmtpFailedRecipientsException(SerializationInfo info, StreamingContext _innerExceptions = (SmtpFailedRecipientException[])info.GetValue("innerExceptions", typeof(SmtpFailedRecipientException[]))!; } - public SmtpFailedRecipientsException(string? message, SmtpFailedRecipientException[] innerExceptions) : - base(message, innerExceptions != null && innerExceptions.Length > 0 ? innerExceptions[0].FailedRecipient : null, - innerExceptions != null && innerExceptions.Length > 0 ? innerExceptions[0] : null) + public SmtpFailedRecipientsException(string? message, SmtpFailedRecipientException[] innerExceptions!!) : + base(message, innerExceptions.Length > 0 ? innerExceptions[0].FailedRecipient : null, innerExceptions.Length > 0 ? innerExceptions[0] : null) { - if (innerExceptions == null) - { - throw new ArgumentNullException(nameof(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 != null && innerExceptions.Count > 0 ? innerExceptions[0].FailedRecipient : null, - innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null) + innerExceptions.Count > 0 ? innerExceptions[0].FailedRecipient : null, + innerExceptions.Count > 0 ? innerExceptions[0] : null) { - if (innerExceptions == null) - { - throw new ArgumentNullException(nameof(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 623bff7d5755d1..529a385e2a7b04 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,15 +29,9 @@ internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManag { } - internal SmtpTransport(SmtpClient client, ISmtpAuthenticationModule[] authenticationModules) + internal SmtpTransport(SmtpClient client, ISmtpAuthenticationModule[] authenticationModules!!) { _client = client; - - if (authenticationModules == null) - { - throw new ArgumentNullException(nameof(authenticationModules)); - } - _authenticationModules = authenticationModules; } @@ -150,19 +144,9 @@ internal void EndGetConnection(IAsyncResult result) _connection!.EndGetConnection(result); } - internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients, + internal IAsyncResult BeginSendMail(MailAddress sender!!, MailAddressCollection recipients!!, string deliveryNotify, bool allowUnicode, AsyncCallback? callback, object? state) { - if (sender == null) - { - throw new ArgumentNullException(nameof(sender)); - } - - if (recipients == null) - { - throw new ArgumentNullException(nameof(recipients)); - } - SendMailAsyncResult result = new SendMailAsyncResult(_connection!, sender, recipients, allowUnicode, _connection!.DSNEnabled ? deliveryNotify : null, callback, state); @@ -201,19 +185,9 @@ internal 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) { - if (sender == null) - { - throw new ArgumentNullException(nameof(sender)); - } - - if (recipients == null) - { - throw new ArgumentNullException(nameof(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 1b7ace1d86e9fd..04193f45d7c6e8 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,13 +26,8 @@ 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) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - _stream = stream; _shouldEncodeLeadingDots = shouldEncodeLeadingDots; _onCloseHandler = new EventHandler(OnClose); @@ -44,16 +39,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(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 028e9456ce3d1e..a9deebd85519a3 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,12 +54,8 @@ public ContentDisposition() // no need to parse disposition since there's nothing to parse } - public ContentDisposition(string disposition) + public ContentDisposition(string disposition!!) { - if (disposition == null) - { - throw new ArgumentNullException(nameof(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 be3092fa306299..e3c1c36c4d6b3c 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 @@ -109,13 +109,8 @@ 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) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - foreach (char c in value) { if (c > 0x7f) @@ -192,10 +187,7 @@ internal ContentType ContentType get { return _contentType ??= new ContentType(); } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _contentType = value; _contentType.PersistIfNeeded((HeaderCollection)Headers, true); @@ -225,13 +217,8 @@ internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callba throw new NotImplementedException(); } - internal void EndSend(IAsyncResult asyncResult) + internal void EndSend(IAsyncResult asyncResult!!) { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(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 84fe52f5f48b9a..81de2524732243 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,13 +101,8 @@ internal TransferEncoding TransferEncoding } } - internal void SetContent(Stream stream) + internal void SetContent(Stream stream!!) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - if (_streamSet) { _stream!.Close(); @@ -119,13 +114,8 @@ 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) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - if (mimeType != null && mimeType != string.Empty) { _contentType = new ContentType(mimeType); @@ -137,12 +127,8 @@ 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) { - if (stream == null) - { - throw new ArgumentNullException(nameof(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 8439cfa8f48f47..19b444795cdc05 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,20 +19,14 @@ 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 { - if (boundary == null) - throw new ArgumentNullException(nameof(boundary)); - _boundaryBytes = Encoding.ASCII.GetBytes(boundary); } - internal override void WriteHeaders(NameValueCollection headers, bool allowUnicode) + internal override void WriteHeaders(NameValueCollection headers!!, bool allowUnicode) { - if (headers == null) - throw new ArgumentNullException(nameof(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 a0127f539bc6c7..684f60e1600cdd 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs @@ -37,13 +37,8 @@ public static string GetHostName() return name; } - public static IPHostEntry GetHostEntry(IPAddress address) + public static IPHostEntry GetHostEntry(IPAddress address!!) { - if (address is null) - { - throw new ArgumentNullException(nameof(address)); - } - if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(address, $"Invalid address '{address}'"); @@ -67,13 +62,8 @@ 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) { - if (hostNameOrAddress is null) - { - throw new ArgumentNullException(nameof(hostNameOrAddress)); - } - // See if it's an IP Address. IPHostEntry ipHostEntry; if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address)) @@ -153,13 +143,8 @@ public static Task GetHostEntryAsync(string hostNameOrAddress, Addr } } - public static Task GetHostEntryAsync(IPAddress address) + public static Task GetHostEntryAsync(IPAddress address!!) { - if (address is null) - { - throw new ArgumentNullException(nameof(address)); - } - if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(address, $"Invalid address '{address}'"); @@ -193,13 +178,8 @@ 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) { - if (hostNameOrAddress is null) - { - throw new ArgumentNullException(nameof(hostNameOrAddress)); - } - // See if it's an IP Address. IPAddress[] addresses; if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address)) @@ -256,13 +236,8 @@ public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) => TaskToApm.End(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult))); [Obsolete("GetHostByName has been deprecated. Use GetHostEntry instead.")] - public static IPHostEntry GetHostByName(string hostName) + public static IPHostEntry GetHostByName(string hostName!!) { - if (hostName is null) - { - throw new ArgumentNullException(nameof(hostName)); - } - if (IPAddress.TryParse(hostName, out IPAddress? address)) { return CreateHostEntryForAddress(address); @@ -280,13 +255,8 @@ public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult) => TaskToApm.End(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult))); [Obsolete("GetHostByAddress has been deprecated. Use GetHostEntry instead.")] - public static IPHostEntry GetHostByAddress(string address) + public static IPHostEntry GetHostByAddress(string address!!) { - if (address is null) - { - throw new ArgumentNullException(nameof(address)); - } - IPHostEntry ipHostEntry = GetHostEntryCore(IPAddress.Parse(address), AddressFamily.Unspecified); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry); @@ -294,13 +264,8 @@ 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!!) { - if (address is null) - { - throw new ArgumentNullException(nameof(address)); - } - IPHostEntry ipHostEntry = GetHostEntryCore(address, AddressFamily.Unspecified); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(address, ipHostEntry); @@ -308,13 +273,8 @@ 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!!) { - if (hostName is null) - { - throw new ArgumentNullException(nameof(hostName)); - } - // See if it's an IP Address. IPHostEntry ipHostEntry; if (IPAddress.TryParse(hostName, out IPAddress? address) && @@ -509,13 +469,8 @@ 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) { - if (hostName is null) - { - throw new ArgumentNullException(nameof(hostName)); - } - if (cancellationToken.IsCancellationRequested) { return justAddresses ? (Task) diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs index 51bde54c68e3a1..125f793c98c962 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs @@ -42,10 +42,7 @@ public Ping() private void CheckArgs(int timeout, byte[] buffer, PingOptions? options) { CheckDisposed(); - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); if (buffer.Length > MaxBufferSize) { @@ -62,10 +59,7 @@ private void CheckArgs(IPAddress address, int timeout, byte[] buffer, PingOption { CheckArgs(timeout, buffer, options); - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); // Check if address family is installed. TestIsIpSupported(address); 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 edfe5ce52551ae..ae305f43ff052b 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieCollection.cs @@ -65,12 +65,8 @@ private void OnSerializing(StreamingContext context) m_version = m_list.Count; } - public void Add(Cookie cookie) + public void Add(Cookie cookie!!) { - if (cookie == null) - { - throw new ArgumentNullException(nameof(cookie)); - } int idx = IndexOf(cookie); if (idx == -1) { @@ -82,12 +78,8 @@ public void Add(Cookie cookie) } } - public void Add(CookieCollection cookies) + public void Add(CookieCollection cookies!!) { - if (cookies == null) - { - throw new ArgumentNullException(nameof(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 68229958f88a72..1a3c86649d5744 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -216,13 +216,8 @@ 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!!) { - if (cookie == null) - { - throw new ArgumentNullException(nameof(cookie)); - } - if (cookie.Domain.Length == 0) { throw new ArgumentException( @@ -580,12 +575,8 @@ private int ExpireCollection(CookieCollection cc) } } - public void Add(CookieCollection cookies) + public void Add(CookieCollection cookies!!) { - if (cookies == null) - { - throw new ArgumentNullException(nameof(cookies)); - } foreach (Cookie c in (ICollection)cookies) { Add(c); @@ -660,33 +651,17 @@ internal bool IsLocalDomain(string host) return false; } - public void Add(Uri uri, Cookie cookie) + public void Add(Uri uri!!, Cookie cookie!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (cookie == null) - { - throw new ArgumentNullException(nameof(cookie)); - } + Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), m_fqdnMyDomain, true, true); Add(new_cookie, true); } - public void Add(Uri uri, CookieCollection cookies) + public void Add(Uri uri!!, CookieCollection cookies!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (cookies == null) - { - throw new ArgumentNullException(nameof(cookies)); - } - bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { @@ -778,12 +753,8 @@ internal CookieCollection CookieCutter(Uri uri, string? headerName, string setCo return cookies; } - public CookieCollection GetCookies(Uri uri) + public CookieCollection GetCookies(Uri uri!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } return InternalGetCookies(uri) ?? new CookieCollection(); } @@ -1014,13 +985,8 @@ private void MergeUpdateCollections(ref CookieCollection? destination, CookieCol } } - public string GetCookieHeader(Uri uri) + public string GetCookieHeader(Uri uri!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - return GetCookieHeader(uri, out _); } @@ -1053,16 +1019,9 @@ 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!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (cookieHeader == null) - { - throw new ArgumentNullException(nameof(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 d12a7b9d0751b3..af7f89cce55abd 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -21,17 +21,8 @@ public CredentialCache() { } - public void Add(Uri uriPrefix, string authType, NetworkCredential cred) + public void Add(Uri uriPrefix!!, string authType!!, NetworkCredential cred) { - if (uriPrefix == null) - { - throw new ArgumentNullException(nameof(uriPrefix)); - } - if (authType == null) - { - throw new ArgumentNullException(nameof(authType)); - } - if ((cred is SystemNetworkCredential) && !((string.Equals(authType, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase)) || (string.Equals(authType, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase)) @@ -141,17 +132,8 @@ 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!!) { - if (uriPrefix == null) - { - throw new ArgumentNullException(nameof(uriPrefix)); - } - if (authType == null) - { - throw new ArgumentNullException(nameof(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 44784173f25dd7..e2762833b7118a 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPAddress.cs @@ -231,13 +231,8 @@ 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!!) { - if (ipString == null) - { - throw new ArgumentNullException(nameof(ipString)); - } - return IPAddressParser.Parse(ipString.AsSpan(), tryParse: false)!; } 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 f5d7637fc1e999..e9b68a1dfd5814 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/IPEndPoint.cs @@ -44,12 +44,8 @@ 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) { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -125,13 +121,8 @@ public static bool TryParse(ReadOnlySpan s, [NotNullWhen(true)] out IPEndP return false; } - public static IPEndPoint Parse(string s) + public static IPEndPoint Parse(string s!!) { - if (s == null) - { - throw new ArgumentNullException(nameof(s)); - } - return Parse(s.AsSpan()); } @@ -153,12 +144,8 @@ public override string ToString() public override SocketAddress Serialize() => new SocketAddress(Address, Port); - public override EndPoint Create(SocketAddress socketAddress) + public override EndPoint Create(SocketAddress socketAddress!!) { - if (socketAddress == null) - { - throw new ArgumentNullException(nameof(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 902cc8f9ddf77a..5ccb653f7b9938 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,13 +48,8 @@ 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) { - if (remoteEndPoint is null) - { - throw new ArgumentNullException(nameof(remoteEndPoint)); - } - IPEndPoint ipEndPoint = GetIPEndPoint(remoteEndPoint); if (ipEndPoint.Address != IPAddress.Loopback) { diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockImplementationProvider.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockImplementationProvider.cs index a46b1691bed6e8..d43fad609913d2 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockImplementationProvider.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockImplementationProvider.cs @@ -16,7 +16,7 @@ internal override QuicListenerProvider CreateListener(QuicListenerOptions option internal override QuicConnectionProvider CreateConnection(QuicClientConnectionOptions options) { - return new MockConnection(options.RemoteEndPoint, + return new MockConnection(options.RemoteEndPoint!, options.ClientAuthenticationOptions, options.LocalEndPoint, options.MaxUnidirectionalStreams, diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs index 66e594c34fca56..421ce00f13a1c2 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicConnection.cs @@ -172,10 +172,7 @@ public MsQuicConnection(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint, MsQ // constructor for outbound connections public MsQuicConnection(QuicClientConnectionOptions options) { - if (options.RemoteEndPoint == null) - { - throw new ArgumentNullException(nameof(options.RemoteEndPoint)); - } + ArgumentNullException.ThrowIfNull(options.RemoteEndPoint, nameof(options.RemoteEndPoint)); _remoteEndPoint = options.RemoteEndPoint; _configuration = SafeMsQuicConfigurationHandle.Create(options); diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs index 7eaf052bfb4d9b..aadd9f1e247582 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicListener.cs @@ -81,10 +81,7 @@ public State(QuicListenerOptions options) internal MsQuicListener(QuicListenerOptions options) { - if (options.ListenEndPoint == null) - { - throw new ArgumentNullException(nameof(options.ListenEndPoint)); - } + ArgumentNullException.ThrowIfNull(options.ListenEndPoint, nameof(options.ListenEndPoint)); _state = new State(options); _stateHandle = GCHandle.Alloc(_state); 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 5c014043519138..dc25c363e4a0f0 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/AuthenticationManager.cs @@ -22,28 +22,16 @@ 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!!) { - if (authenticationModule is null) - { - throw new ArgumentNullException(nameof(authenticationModule)); - } } - public static void Unregister(IAuthenticationModule authenticationModule) + public static void Unregister(IAuthenticationModule authenticationModule!!) { - if (authenticationModule is null) - { - throw new ArgumentNullException(nameof(authenticationModule)); - } } - public static void Unregister(string authenticationScheme) + public static void Unregister(string authenticationScheme!!) { - if (authenticationScheme is null) - { - throw new ArgumentNullException(nameof(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 b0f8f6a7fb6c3a..dbc99ae0a295c9 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -325,10 +325,7 @@ public override ICredentials? Credentials { throw new InvalidOperationException(SR.net_reqsubmitted); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value == CredentialCache.DefaultNetworkCredentials) { throw new ArgumentException(SR.net_ftp_no_defaultcreds, nameof(value)); @@ -686,15 +683,11 @@ 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!!) { try { // parameter validation - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) { @@ -810,16 +803,11 @@ public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, obje return asyncResult; } - public override Stream EndGetRequestStream(IAsyncResult asyncResult) + public override Stream EndGetRequestStream(IAsyncResult asyncResult!!) { Stream? requestStream; try { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } - LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null) @@ -1561,10 +1549,7 @@ public X509CertificateCollection ClientCertificates } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _clientCertificates = value; } } 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 c92ea9f28d5d24..598bb90f5d9035 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -361,10 +361,7 @@ public string Host { throw new InvalidOperationException(SR.net_writestarted); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); Uri? hostUri; if ((value.Contains('/')) || (!TryGetHostUri(value, out hostUri))) @@ -1427,16 +1424,8 @@ 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) { - // - // Do some range checking before assembling the header - // - - if (rangeSpecifier == null) - { - throw new ArgumentNullException(nameof(rangeSpecifier)); - } if ((from < 0) || (to < 0)) { throw new ArgumentOutOfRangeException(from < 0 ? nameof(from) : nameof(to), SR.net_rangetoosmall); @@ -1460,12 +1449,8 @@ 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) { - if (rangeSpecifier == null) - { - throw new ArgumentNullException(nameof(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 0614718c2b95ce..bd9df29bfaa250 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs @@ -143,13 +143,8 @@ 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!!) { - if (requestUriString == null) - { - throw new ArgumentNullException(nameof(requestUriString)); - } - return Create(new Uri(requestUriString), false); } @@ -164,13 +159,8 @@ 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!!) { - if (requestUri == null) - { - throw new ArgumentNullException(nameof(requestUri)); - } - return Create(requestUri, false); } @@ -186,33 +176,20 @@ 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!!) { - if (requestUri == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (requestUriString == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (requestUri == null) - { - throw new ArgumentNullException(nameof(requestUri)); - } if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https")) { throw new NotSupportedException(SR.net_unknown_prefix); @@ -237,21 +214,12 @@ 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!!) { bool Error = false; int i; WebRequestPrefixElement Current; - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - if (creator == null) - { - throw new ArgumentNullException(nameof(creator)); - } - // Lock this object, then walk down PrefixList looking for a place to // to insert this prefix. lock (s_internalSyncObject) 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 b077c9856dc7a7..d5a7477870cbac 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,13 +13,8 @@ public sealed partial class CipherSuitesPolicy internal CipherSuitesPolicyPal Pal { get; private set; } [CLSCompliant(false)] - public CipherSuitesPolicy(IEnumerable allowedCipherSuites) + public CipherSuitesPolicy(IEnumerable allowedCipherSuites!!) { - if (allowedCipherSuites == null) - { - throw new ArgumentNullException(nameof(allowedCipherSuites)); - } - Pal = new CipherSuitesPolicyPal(allowedCipherSuites); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs index 63fa927bf6fdbb..03be81907a3bc5 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStream.cs @@ -602,15 +602,8 @@ private void ValidateCreateContext( throw new InvalidOperationException(SR.net_auth_reauth); } - if (credential == null) - { - throw new ArgumentNullException(nameof(credential)); - } - - if (servicePrincipalName == null) - { - throw new ArgumentNullException(nameof(servicePrincipalName)); - } + ArgumentNullException.ThrowIfNull(credential); + ArgumentNullException.ThrowIfNull(servicePrincipalName); NegotiateStreamPal.ValidateImpersonationLevel(impersonationLevel); if (_context != null && IsServer != isServer) diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs index 58156e3d76a94d..6964b9dc7018c9 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs @@ -54,10 +54,7 @@ private void ValidateCreateContext(SslClientAuthenticationOptions sslClientAuthe throw new InvalidOperationException(SR.net_auth_client_server); } - if (sslClientAuthenticationOptions.TargetHost == null) - { - throw new ArgumentNullException(nameof(sslClientAuthenticationOptions.TargetHost)); - } + ArgumentNullException.ThrowIfNull(sslClientAuthenticationOptions.TargetHost, nameof(sslClientAuthenticationOptions.TargetHost)); _exception = null; try 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 ad4398b2ab41b2..b4535cc31b0f1f 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 @@ -282,13 +282,8 @@ public virtual void AuthenticateAsClient(string targetHost, X509CertificateColle AuthenticateAsClient(options); } - public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions) + public void AuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions!!) { - if (sslClientAuthenticationOptions == null) - { - throw new ArgumentNullException(nameof(sslClientAuthenticationOptions)); - } - SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); @@ -320,13 +315,8 @@ public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool AuthenticateAsServer(options); } - public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions) + public void AuthenticateAsServer(SslServerAuthenticationOptions sslServerAuthenticationOptions!!) { - if (sslServerAuthenticationOptions == null) - { - throw new ArgumentNullException(nameof(sslServerAuthenticationOptions)); - } - SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); @@ -353,13 +343,8 @@ 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) { - if (sslClientAuthenticationOptions == null) - { - throw new ArgumentNullException(nameof(sslClientAuthenticationOptions)); - } - SetAndVerifyValidationCallback(sslClientAuthenticationOptions.RemoteCertificateValidationCallback); SetAndVerifySelectionCallback(sslClientAuthenticationOptions.LocalCertificateSelectionCallback); @@ -408,13 +393,8 @@ 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) { - if (sslServerAuthenticationOptions == null) - { - throw new ArgumentNullException(nameof(sslServerAuthenticationOptions)); - } - SetAndVerifyValidationCallback(sslServerAuthenticationOptions.RemoteCertificateValidationCallback); ValidateCreateContext(CreateAuthenticationOptions(sslServerAuthenticationOptions)); diff --git a/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs b/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs index 9d7f648d87205f..64da83709bc025 100644 --- a/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs +++ b/src/libraries/System.Net.Security/src/System/Net/StreamFramer.cs @@ -73,13 +73,8 @@ internal sealed class StreamFramer return buffer; } - public async Task WriteMessageAsync(TAdapter adapter, byte[] message) where TAdapter : IReadWriteAdapter + public async Task WriteMessageAsync(TAdapter adapter, byte[] message!!) where TAdapter : IReadWriteAdapter { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } - _writeHeader.PayloadSize = message.Length; _writeHeader.CopyTo(_writeHeaderBuffer, 0); diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs index 6a59d81957a4ab..7fcb88eda48737 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs @@ -53,11 +53,7 @@ public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, { throw new ArgumentException(SR.security_ExtendedProtectionPolicy_UseDifferentConstructorForNever, nameof(policyEnforcement)); } - - if (customChannelBinding == null) - { - throw new ArgumentNullException(nameof(customChannelBinding)); - } + ArgumentNullException.ThrowIfNull(customChannelBinding); _policyEnforcement = policyEnforcement; _protectionScenario = ProtectionScenario.TransportSelected; 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 88d8087c42c355..fcf018951d725c 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,13 +12,8 @@ namespace System.Security.Authentication.ExtendedProtection { public class ServiceNameCollection : ReadOnlyCollectionBase { - public ServiceNameCollection(ICollection items) + public ServiceNameCollection(ICollection items!!) { - if (items == null) - { - throw new ArgumentNullException(nameof(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 eb278644472e5f..4d244976958777 100644 --- a/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs +++ b/src/libraries/System.Net.ServicePoint/src/System/Net/ServicePointManager.cs @@ -113,13 +113,8 @@ 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) { - if (address == null) - { - throw new ArgumentNullException(nameof(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 19e8b5ef80dff9..7ffeccc9963acc 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,29 +12,14 @@ 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!!) { - if (group == null) - { - throw new ArgumentNullException(nameof(group)); - } - - if (mcint == null) - { - throw new ArgumentNullException(nameof(mcint)); - } - _group = group; LocalAddress = mcint; } - public MulticastOption(IPAddress group, int interfaceIndex) + public MulticastOption(IPAddress group!!, int interfaceIndex) { - if (group == null) - { - throw new ArgumentNullException(nameof(group)); - } - if (interfaceIndex < 0 || interfaceIndex > 0x00FFFFFF) { throw new ArgumentOutOfRangeException(nameof(interfaceIndex)); @@ -45,13 +30,8 @@ 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!!) { - if (group == null) - { - throw new ArgumentNullException(nameof(group)); - } - _group = group; LocalAddress = IPAddress.Any; @@ -111,13 +91,8 @@ 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) { - if (group == null) - { - throw new ArgumentNullException(nameof(group)); - } - if (ifindex < 0 || ifindex > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException(nameof(ifindex)); @@ -129,13 +104,8 @@ 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!!) { - if (group == null) - { - throw new ArgumentNullException(nameof(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 e7b8b4e8745300..6e57472a199f08 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,12 +41,8 @@ public NetworkStream(Socket socket, FileAccess access) { } - public NetworkStream(Socket socket, FileAccess access, bool ownsSocket) + public NetworkStream(Socket socket!!, FileAccess access, bool ownsSocket) { - if (socket == null) - { - throw new ArgumentNullException(nameof(socket)); - } if (!socket.Blocking) { // Stream.Read*/Write* are incompatible with the semantics of non-blocking sockets, and @@ -422,12 +418,7 @@ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, Asy public override int EndRead(IAsyncResult asyncResult) { ThrowIfDisposed(); - - // Validate input parameters. - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); try { @@ -486,12 +477,7 @@ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, As public override void EndWrite(IAsyncResult asyncResult) { ThrowIfDisposed(); - - // Validate input parameters. - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); try { 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 f528bf0f789e33..1346fc48756b67 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,13 +25,8 @@ 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) { - // We will validate if the file exists on send. - if (filepath == null) - { - throw new ArgumentNullException(nameof(filepath)); - } // The native API will validate the file length on send. if (offset < 0) { @@ -54,13 +49,8 @@ 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) { - // We will validate if the fileStream exists on send. - if (fileStream == null) - { - throw new ArgumentNullException(nameof(fileStream)); - } if (!fileStream.IsAsync) { throw new ArgumentException(SR.net_sockets_sendpackelement_FileStreamMustBeAsync, nameof(fileStream)); @@ -87,12 +77,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(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 cb04d92d744c23..4b8dd5d73e623c 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 @@ -162,10 +162,7 @@ public ValueTask ConnectAsync(IPAddress[] addresses, int port, CancellationToken { ThrowIfDisposed(); - if (addresses == null) - { - throw new ArgumentNullException(nameof(addresses)); - } + ArgumentNullException.ThrowIfNull(addresses); if (addresses.Length == 0) { @@ -238,13 +235,8 @@ 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) { - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } - EndPoint ep = IPAddress.TryParse(host, out IPAddress? parsedAddress) ? (EndPoint) new IPEndPoint(parsedAddress, port) : new DnsEndPoint(host, port); @@ -626,13 +618,8 @@ 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) { - if (remoteEP is null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } - if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); @@ -739,12 +726,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if ((uint)offset > (uint)buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); @@ -758,10 +741,7 @@ private static void ValidateBufferArguments(byte[] buffer, int offset, int size) /// Validates the supplied array segment, throwing if its array or indices are null or out-of-bounds, respectively. private static void ValidateBuffer(ArraySegment buffer) { - if (buffer.Array == null) - { - throw new ArgumentNullException(nameof(buffer.Array)); - } + ArgumentNullException.ThrowIfNull(buffer.Array, nameof(buffer.Array)); if ((uint)buffer.Offset > (uint)buffer.Array.Length) { throw new ArgumentOutOfRangeException(nameof(buffer.Offset)); @@ -773,12 +753,8 @@ 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!!) { - if (buffers == null) - { - throw new ArgumentNullException(nameof(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 f3ecb8e64a9f05..d134a225499bde 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 @@ -747,12 +747,7 @@ public void Bind(EndPoint localEP) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP); ThrowIfDisposed(); - - // Validate input parameters. - if (localEP == null) - { - throw new ArgumentNullException(nameof(localEP)); - } + ArgumentNullException.ThrowIfNull(localEP); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"localEP:{localEP}"); @@ -793,12 +788,7 @@ private void DoBind(EndPoint endPointSnapshot, Internals.SocketAddress socketAdd public void Connect(EndPoint remoteEP) { ThrowIfDisposed(); - - // Validate input parameters. - if (remoteEP == null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } + ArgumentNullException.ThrowIfNull(remoteEP); if (_isDisconnected) { @@ -845,11 +835,7 @@ public void Connect(EndPoint remoteEP) public void Connect(IPAddress address, int port) { ThrowIfDisposed(); - - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); if (!TcpValidationHelpers.ValidatePortNumber(port)) { @@ -875,11 +861,8 @@ public void Connect(IPAddress address, int port) public void Connect(string host, int port) { ThrowIfDisposed(); + ArgumentNullException.ThrowIfNull(host); - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -907,11 +890,8 @@ public void Connect(string host, int port) public void Connect(IPAddress[] addresses, int port) { ThrowIfDisposed(); + ArgumentNullException.ThrowIfNull(addresses); - if (addresses == null) - { - throw new ArgumentNullException(nameof(addresses)); - } if (addresses.Length == 0) { throw new ArgumentException(SR.net_sockets_invalid_ipaddress_length, nameof(addresses)); @@ -1115,11 +1095,7 @@ public int Send(IList> buffers, SocketFlags socketFlags) public int Send(IList> buffers, SocketFlags socketFlags, out SocketError errorCode) { ThrowIfDisposed(); - - if (buffers == null) - { - throw new ArgumentNullException(nameof(buffers)); - } + ArgumentNullException.ThrowIfNull(buffers); if (buffers.Count == 0) { @@ -1309,10 +1285,7 @@ public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, ThrowIfDisposed(); ValidateBufferArguments(buffer, offset, size); - if (remoteEP == null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } + ArgumentNullException.ThrowIfNull(remoteEP); ValidateBlockingMode(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"SRC:{LocalEndPoint} size:{size} remoteEP:{remoteEP}"); @@ -1385,10 +1358,7 @@ public int SendTo(ReadOnlySpan buffer, EndPoint remoteEP) public int SendTo(ReadOnlySpan buffer, SocketFlags socketFlags, EndPoint remoteEP) { ThrowIfDisposed(); - if (remoteEP == null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } + ArgumentNullException.ThrowIfNull(remoteEP); ValidateBlockingMode(); @@ -1531,11 +1501,7 @@ public int Receive(IList> buffers, SocketFlags socketFlags) public int Receive(IList> buffers, SocketFlags socketFlags, out SocketError errorCode) { ThrowIfDisposed(); - - if (buffers == null) - { - throw new ArgumentNullException(nameof(buffers)); - } + ArgumentNullException.ThrowIfNull(buffers); if (buffers.Count == 0) { @@ -1652,11 +1618,8 @@ public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFla public int ReceiveMessageFrom(Span buffer, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation) { ThrowIfDisposed(); + ArgumentNullException.ThrowIfNull(remoteEP); - if (remoteEP == null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } if (!CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), nameof(remoteEP)); @@ -1946,12 +1909,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue) { ThrowIfDisposed(); - - // Validate input parameters. - if (optionValue == null) - { - throw new ArgumentNullException(nameof(optionValue)); - } + ArgumentNullException.ThrowIfNull(optionValue); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"optionLevel:{optionLevel} optionName:{optionName} optionValue:{optionValue}"); @@ -2339,11 +2297,7 @@ public IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? p public void EndSendFile(IAsyncResult asyncResult) { ThrowIfDisposed(); - - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } + ArgumentNullException.ThrowIfNull(asyncResult); TaskToApm.End(asyncResult); } @@ -2352,10 +2306,7 @@ public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags { ThrowIfDisposed(); ValidateBufferArguments(buffer, offset, size); - if (remoteEP == null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } + ArgumentNullException.ThrowIfNull(remoteEP); Task t = SendToAsync(buffer.AsMemory(offset, size), socketFlags, remoteEP).AsTask(); return TaskToApm.Begin(t, callback, state); @@ -2469,10 +2420,7 @@ public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation) { ThrowIfDisposed(); - if (endPoint == null) - { - throw new ArgumentNullException(nameof(endPoint)); - } + ArgumentNullException.ThrowIfNull(endPoint); if (!CanTryAddressFamily(endPoint.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint)); @@ -2510,11 +2458,7 @@ public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) { ThrowIfDisposed(); - // Validate input parameters. - if (endPoint == null) - { - throw new ArgumentNullException(nameof(endPoint)); - } + ArgumentNullException.ThrowIfNull(endPoint); if (!CanTryAddressFamily(endPoint.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint)); @@ -2628,10 +2572,7 @@ private bool AcceptAsync(SocketAsyncEventArgs e, CancellationToken cancellationT { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.HasMultipleBuffers) { throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); @@ -2683,18 +2624,12 @@ internal bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket, bool saeaCan ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.HasMultipleBuffers) { throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); } - if (e.RemoteEndPoint == null) - { - throw new ArgumentNullException("remoteEP"); - } + ArgumentNullException.ThrowIfNull(e.RemoteEndPoint, "remoteEP"); if (_isListening) { throw new InvalidOperationException(SR.net_sockets_mustnotlisten); @@ -2785,14 +2720,8 @@ 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!!) { - bool pending; - - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } if (e.HasMultipleBuffers) { throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); @@ -2805,6 +2734,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint? dnsEP = endPointSnapshot as DnsEndPoint; + bool pending; if (dnsEP != null) { Socket? attemptSocket = dnsEP.AddressFamily != AddressFamily.Unspecified ? new Socket(dnsEP.AddressFamily, socketType, protocolType) : null; @@ -2832,12 +2762,8 @@ 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!!) { - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } e.CancelConnectAsync(); } @@ -2848,10 +2774,7 @@ private bool DisconnectAsync(SocketAsyncEventArgs e, CancellationToken cancellat // Throw if socket disposed ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); // Prepare for and make the native call. e.StartOperationCommon(this, SocketAsyncOperation.Disconnect); @@ -2876,10 +2799,7 @@ private bool ReceiveAsync(SocketAsyncEventArgs e, CancellationToken cancellation { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); // Prepare for and make the native call. e.StartOperationCommon(this, SocketAsyncOperation.Receive); @@ -2904,10 +2824,7 @@ private bool ReceiveFromAsync(SocketAsyncEventArgs e, CancellationToken cancella { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.RemoteEndPoint == null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); @@ -2953,10 +2870,7 @@ private bool ReceiveMessageFromAsync(SocketAsyncEventArgs e, CancellationToken c { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.RemoteEndPoint == null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); @@ -3003,10 +2917,7 @@ private bool SendAsync(SocketAsyncEventArgs e, CancellationToken cancellationTok { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); // Prepare for and make the native call. e.StartOperationCommon(this, SocketAsyncOperation.Send); @@ -3031,10 +2942,7 @@ private bool SendPacketsAsync(SocketAsyncEventArgs e, CancellationToken cancella { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.SendPacketsElements == null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.SendPacketsElements"), nameof(e)); @@ -3067,10 +2975,7 @@ private bool SendToAsync(SocketAsyncEventArgs e, CancellationToken cancellationT { ThrowIfDisposed(); - if (e == null) - { - throw new ArgumentNullException(nameof(e)); - } + ArgumentNullException.ThrowIfNull(e); if (e.RemoteEndPoint == null) { throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); @@ -3744,10 +3649,7 @@ private bool CheckErrorAndUpdateStatus(SocketError errorCode) // and check whether the socket is bound. private void ValidateReceiveFromEndpointAndState(EndPoint remoteEndPoint, string remoteEndPointArgumentName) { - if (remoteEndPoint == null) - { - throw new ArgumentNullException(remoteEndPointArgumentName); - } + ArgumentNullException.ThrowIfNull(remoteEndPoint, remoteEndPointArgumentName); if (!CanTryAddressFamily(remoteEndPoint.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEndPoint.AddressFamily, _addressFamily), remoteEndPointArgumentName); 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 51ffe1126953c5..576b44bc67339d 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 @@ -45,15 +45,9 @@ 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!!) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP); - - if (localEP == null) - { - throw new ArgumentNullException(nameof(localEP)); - } - _family = localEP.AddressFamily; // set before calling CreateSocket InitializeClientSocket(); _clientSocket.Bind(localEP); @@ -61,14 +55,9 @@ 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) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, hostname); - - if (hostname == null) - { - throw new ArgumentNullException(nameof(hostname)); - } if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -131,13 +120,9 @@ public bool ExclusiveAddressUse // Connects the Client to the specified port on the specified host. public void Connect(string hostname, int port) { - ThrowIfDisposed(); - if (hostname == null) - { - throw new ArgumentNullException(nameof(hostname)); - } + ArgumentNullException.ThrowIfNull(hostname); if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -231,10 +216,7 @@ public void Connect(IPAddress address, int port) { ThrowIfDisposed(); - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -249,10 +231,7 @@ public void Connect(IPEndPoint remoteEP) { ThrowIfDisposed(); - if (remoteEP == null) - { - throw new ArgumentNullException(nameof(remoteEP)); - } + ArgumentNullException.ThrowIfNull(remoteEP); Client.Connect(remoteEP); _family = Client.AddressFamily; diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs index d0f60437899edd..6eaa540d4cbb14 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/TCPListener.cs @@ -24,10 +24,7 @@ public TcpListener(IPEndPoint localEP) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localEP); - if (localEP == null) - { - throw new ArgumentNullException(nameof(localEP)); - } + ArgumentNullException.ThrowIfNull(localEP); _serverSocketEP = localEP; _serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } @@ -38,10 +35,7 @@ public TcpListener(IPAddress localaddr, int port) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, localaddr); - if (localaddr == null) - { - throw new ArgumentNullException(nameof(localaddr)); - } + ArgumentNullException.ThrowIfNull(localaddr); if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(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 e662dcb648173f..b4a6c31422b540 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 @@ -84,14 +84,8 @@ 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!!) { - // Validate input parameters. - if (localEP == null) - { - throw new ArgumentNullException(nameof(localEP)); - } - // IPv6 Changes: Set the AddressFamily of this object before // creating the client socket. _family = localEP.AddressFamily; @@ -318,10 +312,7 @@ private void ValidateDatagram(byte[] datagram, int bytes, IPEndPoint? endPoint) { ThrowIfDisposed(); - if (datagram == null) - { - throw new ArgumentNullException(nameof(datagram)); - } + ArgumentNullException.ThrowIfNull(datagram); if (bytes > datagram.Length || bytes < 0) { @@ -420,11 +411,7 @@ public void JoinMulticastGroup(IPAddress multicastAddr) { // Validate input parameters. ThrowIfDisposed(); - - if (multicastAddr == null) - { - throw new ArgumentNullException(nameof(multicastAddr)); - } + ArgumentNullException.ThrowIfNull(multicastAddr); // IPv6 Changes: we need to create the correct MulticastOption and // must also check for address family compatibility. @@ -479,10 +466,7 @@ public void JoinMulticastGroup(int ifindex, IPAddress multicastAddr) ThrowIfDisposed(); // Validate input parameters. - if (multicastAddr == null) - { - throw new ArgumentNullException(nameof(multicastAddr)); - } + ArgumentNullException.ThrowIfNull(multicastAddr); if (ifindex < 0) { @@ -510,10 +494,7 @@ public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive) ThrowIfDisposed(); // parameter validation; - if (multicastAddr == null) - { - throw new ArgumentNullException(nameof(multicastAddr)); - } + ArgumentNullException.ThrowIfNull(multicastAddr); if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255)) { throw new ArgumentOutOfRangeException(nameof(timeToLive)); @@ -535,10 +516,7 @@ public void DropMulticastGroup(IPAddress multicastAddr) ThrowIfDisposed(); // Validate input parameters. - if (multicastAddr == null) - { - throw new ArgumentNullException(nameof(multicastAddr)); - } + ArgumentNullException.ThrowIfNull(multicastAddr); // IPv6 Changes: we need to create the correct MulticastOption and // must also check for address family compatibility. @@ -573,10 +551,7 @@ public void DropMulticastGroup(IPAddress multicastAddr, int ifindex) ThrowIfDisposed(); // Validate input parameters. - if (multicastAddr == null) - { - throw new ArgumentNullException(nameof(multicastAddr)); - } + ArgumentNullException.ThrowIfNull(multicastAddr); if (ifindex < 0) { @@ -750,10 +725,7 @@ private void CreateClientSocket() public UdpClient(string hostname, int port) { - if (hostname == null) - { - throw new ArgumentNullException(nameof(hostname)); - } + ArgumentNullException.ThrowIfNull(hostname); if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -775,10 +747,7 @@ public void Connect(string hostname, int port) { ThrowIfDisposed(); - if (hostname == null) - { - throw new ArgumentNullException(nameof(hostname)); - } + ArgumentNullException.ThrowIfNull(hostname); if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -904,10 +873,7 @@ public void Connect(IPAddress addr, int port) { ThrowIfDisposed(); - if (addr == null) - { - throw new ArgumentNullException(nameof(addr)); - } + ArgumentNullException.ThrowIfNull(addr); if (!TcpValidationHelpers.ValidatePortNumber(port)) { throw new ArgumentOutOfRangeException(nameof(port)); @@ -922,10 +888,7 @@ public void Connect(IPEndPoint endPoint) { ThrowIfDisposed(); - if (endPoint == null) - { - throw new ArgumentNullException(nameof(endPoint)); - } + ArgumentNullException.ThrowIfNull(endPoint); CheckForBroadcast(endPoint.Address); Client.Connect(endPoint); @@ -973,10 +936,7 @@ public int Send(byte[] dgram, int bytes, IPEndPoint? endPoint) { ThrowIfDisposed(); - if (dgram == null) - { - throw new ArgumentNullException(nameof(dgram)); - } + ArgumentNullException.ThrowIfNull(dgram); if (_active && endPoint != null) { // Do not allow sending packets to arbitrary host when connected @@ -1052,10 +1012,7 @@ public int Send(byte[] dgram, int bytes) { ThrowIfDisposed(); - if (dgram == null) - { - throw new ArgumentNullException(nameof(dgram)); - } + ArgumentNullException.ThrowIfNull(dgram); if (!_active) { // only allowed on connected socket 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 55535f0583009e..060012e96967ea 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,18 +18,8 @@ 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!!) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - if (remoteEndPoint == null) - { - throw new ArgumentNullException(nameof(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 f400873433c6e5..b69e6d82965b24 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,13 +22,8 @@ public UnixDomainSocketEndPoint(string path) : this(path, null) { } - private UnixDomainSocketEndPoint(string path, string? boundFileName) + private UnixDomainSocketEndPoint(string path!!, string? boundFileName) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } - BoundFileName = boundFileName; // Pathname socket addresses should be null-terminated. @@ -61,13 +56,8 @@ private UnixDomainSocketEndPoint(string path, string? boundFileName) internal static int MaxAddressSize => s_nativeAddressSize; - internal UnixDomainSocketEndPoint(SocketAddress socketAddress) + internal UnixDomainSocketEndPoint(SocketAddress socketAddress!!) { - if (socketAddress == null) - { - throw new ArgumentNullException(nameof(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 d23488f44c02ce..c597c50beb5e97 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -278,10 +278,8 @@ 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 { @@ -318,11 +316,8 @@ 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; @@ -357,10 +352,8 @@ 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 @@ -390,13 +383,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); WebRequest? request = null; StartOperation(); @@ -430,14 +419,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); StartOperation(); try @@ -551,14 +535,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); FileStream? fs = null; WebRequest? request = null; @@ -624,14 +603,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); WebRequest? request = null; StartOperation(); @@ -663,14 +637,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); StartOperation(); try @@ -689,10 +658,8 @@ 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 { @@ -779,10 +746,8 @@ private void CopyHeadersTo(WebRequest request) } } - private Uri GetUri(string address) + private Uri GetUri(string address!!) { - ArgumentNullException.ThrowIfNull(address); - Uri? uri; if (_baseAddress != null) { @@ -799,10 +764,8 @@ 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)) @@ -1295,10 +1258,8 @@ 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 { @@ -1333,13 +1294,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); try @@ -1394,10 +1351,8 @@ 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 { @@ -1420,10 +1375,8 @@ 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 { @@ -1446,11 +1399,8 @@ 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 @@ -1472,14 +1422,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); try @@ -1523,14 +1468,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); try @@ -1564,14 +1504,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); FileStream? fs = null; AsyncOperation asyncOp = StartAsyncOperation(userToken); @@ -1603,14 +1538,9 @@ 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); - if (method == null) - { - method = MapToDefaultMethod(address); - } + method ??= MapToDefaultMethod(address); AsyncOperation asyncOp = StartAsyncOperation(userToken); try 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 a8b9d60651d8b0..195fe6979961ed 100644 --- a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs +++ b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.cs @@ -92,13 +92,8 @@ public bool UseDefaultCredentials set => Credentials = value ? CredentialCache.DefaultCredentials : null; } - public Uri? GetProxy(Uri destination) + public Uri? GetProxy(Uri destination!!) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - return IsBypassed(destination) ? destination : Address; } @@ -176,13 +171,8 @@ private bool IsMatchInBypassList(Uri input) return false; } - public bool IsBypassed(Uri host) + public bool IsBypassed(Uri host!!) { - if (host == null) - { - throw new ArgumentNullException(nameof(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 7159283212d601..1db846074a6446 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,12 +50,8 @@ public override WebSocketState State } } - public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) + public Task ConnectAsync(Uri uri!!, CancellationToken cancellationToken) { - if (uri == null) - { - throw new ArgumentNullException(nameof(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 5f24f9a98083a3..0627dca37a8c71 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,13 +138,8 @@ 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) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(stream)); @@ -168,14 +163,8 @@ public static WebSocket CreateFromStream(Stream stream, bool isServer, string? s /// 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!!) { - if (stream is null) - throw new ArgumentNullException(nameof(stream)); - - if (options is null) - throw new ArgumentNullException(nameof(options)); - if (!stream.CanRead || !stream.CanWrite) throw new ArgumentException(!stream.CanRead ? SR.NotReadableStream : SR.NotWriteableStream, nameof(stream)); @@ -196,15 +185,10 @@ 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) { - if (innerStream == null) - { - throw new ArgumentNullException(nameof(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 925512c9956fc5..88a46e604acd56 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,12 +100,8 @@ 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 == 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 83c6947d76a50c..cb31580bc9d9cd 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,13 +308,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(fromArray)); - } - if (fromArray.Rank == 0) { throw new ArgumentException(SR.ArrayMustContainElements, nameof(fromArray)); @@ -636,24 +631,16 @@ 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 == null) - { - throw new ArgumentNullException(nameof(indices)); - } var span = new ReadOnlySpan(indices); return this[span]; } set { - if (indices == null) - { - throw new ArgumentNullException(nameof(indices)); - } var span = new ReadOnlySpan(indices); this[span] = value; } @@ -930,12 +917,8 @@ 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 == 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 bff227728ecff7..8e7fbef4f2755c 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/CollectionHelpers.cs @@ -7,13 +7,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 3ab6a770ca772b..e9c1554d7925bb 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/Generic/DebugView.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/Generic/DebugView.cs @@ -9,9 +9,9 @@ internal sealed class CollectionDebugView { private readonly ICollection _collection; - public CollectionDebugView(ICollection collection) + public CollectionDebugView(ICollection collection!!) { - _collection = collection ?? throw new ArgumentNullException(nameof(collection)); + _collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] 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 3c0c0a4068a755..266c58fa3e95c4 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/ObjectModel/KeyedCollection.cs @@ -69,13 +69,8 @@ public TItem this[TKey key] } } - public bool Contains(TKey key) + public bool Contains(TKey key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - if (dict != null) { return dict.ContainsKey(key); @@ -92,13 +87,8 @@ 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) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - if (dict != null) { return dict.TryGetValue(key, out item!); @@ -135,13 +125,8 @@ private bool ContainsItem(TItem item) return false; } - public bool Remove(TKey key) + public bool Remove(TKey key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(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 b5e6eb8747e3d9..1de8f8294be540 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(CreateCopy(collection, nameof(collection))) + public ObservableCollection(IEnumerable collection!!) : base(new List(collection)) { } @@ -58,20 +58,10 @@ public ObservableCollection(IEnumerable collection) : base(CreateCopy(collect /// same order they are read by the enumerator of the list. /// /// list is a null reference - public ObservableCollection(List list) : base(CreateCopy(list, nameof(list))) + public ObservableCollection(List list!!) : base(new List(list)) { } - private static List CreateCopy(IEnumerable collection, string paramName) - { - if (collection == null) - { - throw new ArgumentNullException(paramName); - } - - return new List(collection); - } - /// /// Move item at oldIndex to newIndex. /// diff --git a/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs b/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs index 60b9898affd997..49476957e60799 100644 --- a/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs +++ b/src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs @@ -114,10 +114,7 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: - if (changedItems == null) - { - throw new ArgumentNullException(nameof(changedItems)); - } + ArgumentNullException.ThrowIfNull(changedItems); if (startingIndex < -1) { throw new ArgumentException(SR.IndexCannotBeNegative, nameof(startingIndex)); @@ -197,14 +194,8 @@ public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IL { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); } - if (newItems == null) - { - throw new ArgumentNullException(nameof(newItems)); - } - if (oldItems == null) - { - throw new ArgumentNullException(nameof(oldItems)); - } + ArgumentNullException.ThrowIfNull(newItems); + ArgumentNullException.ThrowIfNull(oldItems); _action = action; _newItems = new ReadOnlyList(newItems); diff --git a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs index 36fa3052c73f53..741741992fa137 100644 --- a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeConverterAttribute.cs @@ -32,13 +32,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - ConverterTypeName = type.AssemblyQualifiedName!; } @@ -47,13 +42,8 @@ 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!!) { - if (typeName == null) - { - throw new ArgumentNullException(nameof(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 5f42f291038524..2a7e742d19cc31 100644 --- a/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs +++ b/src/libraries/System.ObjectModel/src/System/ComponentModel/TypeDescriptionProviderAttribute.cs @@ -11,26 +11,16 @@ public sealed class TypeDescriptionProviderAttribute : Attribute /// /// Creates a new TypeDescriptionProviderAttribute object. /// - public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string typeName) + public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] string typeName!!) { - if (typeName == null) - { - throw new ArgumentNullException(nameof(typeName)); - } - TypeName = typeName; } /// /// Creates a new TypeDescriptionProviderAttribute object. /// - public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type) + public TypeDescriptionProviderAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - TypeName = type.AssemblyQualifiedName!; } diff --git a/src/libraries/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComponentActivator.cs b/src/libraries/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComponentActivator.cs index 8b35a94463c996..25c9a0330bd3ce 100644 --- a/src/libraries/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComponentActivator.cs +++ b/src/libraries/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComponentActivator.cs @@ -36,10 +36,7 @@ public static class ComponentActivator private static string MarshalToString(IntPtr arg, string argName) { string? result = Marshal.PtrToStringAuto(arg); - if (result == null) - { - throw new ArgumentNullException(argName); - } + ArgumentNullException.ThrowIfNull(result, argName); return result; } 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 e36440a56a822f..2bfc2697ceb86f 100644 --- a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs +++ b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs @@ -435,11 +435,8 @@ 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!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (name != null && name.Length > MaxValueLength) throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name)); diff --git a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx index 7b47a57ac9632e..0ed9167649a7d3 100644 --- a/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx @@ -1597,9 +1597,6 @@ Value cannot be null. - - Key cannot be null. - Path cannot be null. @@ -3292,9 +3289,6 @@ The tookLock argument must be set to false before calling this method. - - The condition argument is null. - The timeout must represent a value between -1 and Int32.MaxValue, inclusive. 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 883557c3e29f6b..0bb3b555796705 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs @@ -16,11 +16,8 @@ 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) { - if (type is null) - throw new ArgumentNullException(nameof(type)); - if (type is System.Reflection.Emit.TypeBuilder) throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder); @@ -89,11 +86,8 @@ 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) { - if (type is null) - throw new ArgumentNullException(nameof(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 0fc24781a1677c..1bbae039b0d693 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AggregateException.cs @@ -51,14 +51,9 @@ 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) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } - _innerExceptions = new[] { innerException }; } @@ -71,7 +66,7 @@ public AggregateException(string? message, Exception innerException) /// is null. /// An element of is /// null. - public AggregateException(IEnumerable innerExceptions) : + public AggregateException(IEnumerable innerExceptions!!) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } @@ -85,7 +80,7 @@ public AggregateException(IEnumerable innerExceptions) : /// is null. /// An element of is /// null. - public AggregateException(params Exception[] innerExceptions) : + public AggregateException(params Exception[] innerExceptions!!) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } @@ -100,8 +95,8 @@ public AggregateException(params Exception[] innerExceptions) : /// is null. /// An element of is /// null. - public AggregateException(string? message, IEnumerable innerExceptions) - : this(message, innerExceptions == null ? null : new List(innerExceptions).ToArray(), cloneExceptions: false) + public AggregateException(string? message, IEnumerable innerExceptions!!) + : this(message, new List(innerExceptions).ToArray(), cloneExceptions: false) { } @@ -115,19 +110,14 @@ public AggregateException(string? message, IEnumerable innerException /// is null. /// An element of is /// null. - public AggregateException(string? message, params Exception[] innerExceptions) : + public AggregateException(string? message, params Exception[] innerExceptions!!) : this(message, innerExceptions, cloneExceptions: true) { } - private AggregateException(string? message, Exception[]? innerExceptions, bool cloneExceptions) : - base(message, innerExceptions?.Length > 0 ? innerExceptions[0] : null) + private AggregateException(string? message, Exception[] innerExceptions, bool cloneExceptions) : + base(message, innerExceptions.Length > 0 ? innerExceptions[0] : null) { - if (innerExceptions == null) - { - throw new ArgumentNullException(nameof(innerExceptions)); - } - _innerExceptions = cloneExceptions ? new Exception[innerExceptions.Length] : innerExceptions; for (int i = 0; i < _innerExceptions.Length; i++) @@ -263,13 +253,8 @@ public override Exception GetBaseException() /// cref="AggregateException"/> was not handled. /// The argument is /// null. - public void Handle(Func predicate) + public void Handle(Func predicate!!) { - if (predicate == null) - { - throw new ArgumentNullException(nameof(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 87488c1dfe280a..a08587ef454c3e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs @@ -29,11 +29,8 @@ 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!!) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (s_dataStore == null) return null; @@ -51,11 +48,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(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 cff98ca55ee2f8..27b1a979d49e3f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs @@ -90,9 +90,8 @@ 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!!) { - if (friendlyName == null) throw new ArgumentNullException(nameof(friendlyName)); throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains); } @@ -100,12 +99,8 @@ 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) { - if (assemblyFile == null) - { - throw new ArgumentNullException(nameof(assemblyFile)); - } string fullPath = Path.GetFullPath(assemblyFile); Assembly assembly = Assembly.LoadFile(fullPath); return ExecuteAssembly(assembly, args); @@ -162,12 +157,8 @@ 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!!) { - if (domain == null) - { - throw new ArgumentNullException(nameof(domain)); - } throw new CannotUnloadAppDomainException(SR.Arg_PlatformNotSupported); } @@ -264,13 +255,8 @@ public void SetPrincipalPolicy(PrincipalPolicy policy) _principalPolicy = policy; } - public void SetThreadPrincipal(IPrincipal principal) + public void SetThreadPrincipal(IPrincipal principal!!) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } - // Set the principal while checking it has not been set previously. if (Interlocked.CompareExchange(ref _defaultPrincipal, principal, null) is not null) { @@ -279,24 +265,14 @@ 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) { - if (assemblyName == null) - { - throw new ArgumentNullException(nameof(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) { - if (assemblyName == null) - { - throw new ArgumentNullException(nameof(assemblyName)); - } - return Activator.CreateInstance(assemblyName, typeName, ignoreCase, @@ -308,13 +284,8 @@ 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) { - if (assemblyName == null) - { - throw new ArgumentNullException(nameof(assemblyName)); - } - return Activator.CreateInstance(assemblyName, typeName, activationAttributes); } diff --git a/src/libraries/System.Private.CoreLib/src/System/ArgumentNullException.cs b/src/libraries/System.Private.CoreLib/src/System/ArgumentNullException.cs index 46b7c66cf6dfae..f92576643b2a20 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ArgumentNullException.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ArgumentNullException.cs @@ -76,6 +76,17 @@ public static unsafe void ThrowIfNull([NotNull] void* argument, [CallerArgumentE } } + /// Throws an if is null. + /// The pointer argument to validate as non-null. + /// The name of the parameter with which corresponds. + internal static unsafe void ThrowIfNull(IntPtr argument, [CallerArgumentExpression("argument")] string? paramName = null) + { + if (argument == IntPtr.Zero) + { + Throw(paramName); + } + } + [DoesNotReturn] private static void Throw(string? paramName) => throw new ArgumentNullException(paramName); diff --git a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs index 3aba604700de41..09b10385daa998 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Boolean.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Boolean.cs @@ -198,9 +198,8 @@ 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!!) { - if (value == null) throw new ArgumentNullException(nameof(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 027c138d1ac6aa..4aa0a9f6e991d6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffer.cs @@ -19,13 +19,8 @@ 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) { - if (src == null) - throw new ArgumentNullException(nameof(src)); - if (dst == null) - throw new ArgumentNullException(nameof(dst)); - nuint uSrcLen = src.NativeLength; if (src.GetType() != typeof(byte[])) { @@ -63,12 +58,8 @@ public static unsafe void BlockCopy(Array src, int srcOffset, Array dst, int dst 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!!) { - // Is the array present? - if (array == null) - throw new ArgumentNullException(nameof(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 d4678fee3ef173..af1372f10528fb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffers/ConfigurableArrayPool.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffers/ConfigurableArrayPool.cs @@ -120,13 +120,9 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - else if (array.Length == 0) + if (array.Length == 0) { // Ignore empty arrays. When a zero-length array is rented, we return a singleton // rather than actually taking a buffer out of the lowest bucket. 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 58db6fa5f9c7f9..cb24e7610991e8 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,13 +21,8 @@ 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) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 67365bc719f7e6..f8da94c59278af 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs @@ -60,11 +60,8 @@ 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!!) { - if (c == null) - throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); - int count = c.Count; if (count == 0) { @@ -152,10 +149,8 @@ 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!!) { - if (list == null) - throw new ArgumentNullException(nameof(list)); return new IListWrapper(list); } @@ -324,20 +319,16 @@ 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!!) { - if (list == null) - throw new ArgumentNullException(nameof(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!!) { - if (list == null) - throw new ArgumentNullException(nameof(list)); return new FixedSizeArrayList(list); } @@ -437,10 +428,8 @@ 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!!) { - if (c == null) - throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); int count = c.Count; @@ -515,19 +504,15 @@ 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!!) { - if (list == null) - throw new ArgumentNullException(nameof(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!!) { - if (list == null) - throw new ArgumentNullException(nameof(list)); return new ReadOnlyArrayList(list); } @@ -624,10 +609,8 @@ 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!!) { - if (c == null) throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); - int count = c.Count; if (index < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -684,19 +667,15 @@ 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!!) { - if (list == null) - throw new ArgumentNullException(nameof(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!!) { - if (list == null) - throw new ArgumentNullException(nameof(list)); return new SyncArrayList(list); } @@ -856,10 +835,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0 || arrayIndex < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -930,10 +907,8 @@ 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!!) { - if (c == null) - throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); if (index < 0 || index > Count) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); if (c.Count > 0) @@ -1042,13 +1017,8 @@ 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!!) { - if (c == null) - { - throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection); - } - if (index < 0 || index > _list.Count - c.Count) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); @@ -2243,13 +2213,8 @@ public override int Add(object? value) return _baseSize++; } - public override void AddRange(ICollection c) + public override void AddRange(ICollection c!!) { - if (c == null) - { - throw new ArgumentNullException(nameof(c)); - } - InternalUpdateRange(); int count = c.Count; if (count > 0) @@ -2323,10 +2288,8 @@ public override bool Contains(object? item) } } - public override void CopyTo(Array array, int index) + public override void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) @@ -2338,10 +2301,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0 || count < 0) @@ -2448,10 +2409,7 @@ public override void Insert(int index, object? value) public override void InsertRange(int index, ICollection c) { if (index < 0 || index > _baseSize) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); - if (c == null) - { - throw new ArgumentNullException(nameof(c)); - } + ArgumentNullException.ThrowIfNull(c); InternalUpdateRange(); int count = c.Count; @@ -2697,11 +2655,8 @@ internal sealed class ArrayListDebugView { private readonly ArrayList _arrayList; - public ArrayListDebugView(ArrayList arrayList) + public ArrayListDebugView(ArrayList arrayList!!) { - if (arrayList == null) - throw new ArgumentNullException(nameof(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 26997e6e240c5d..0403fc238a39d2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Comparer.cs @@ -21,27 +21,18 @@ 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!!) { - if (culture == null) - throw new ArgumentNullException(nameof(culture)); - _compareInfo = culture.CompareInfo; } - private Comparer(SerializationInfo info, StreamingContext context) + private Comparer(SerializationInfo info!!, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - _compareInfo = (CompareInfo)info.GetValue("CompareInfo", typeof(CompareInfo))!; } - public void GetObjectData(SerializationInfo info, StreamingContext context) + public void GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(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 d10a30629a65bd..27834f8d62a0d7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/CompatibleComparer.cs @@ -44,13 +44,8 @@ public int Compare(object? a, object? b) throw new ArgumentException(SR.Argument_ImplementIComparable); } - public int GetHashCode(object obj) + public int GetHashCode(object obj!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(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 a33f499665d193..cbd0024ded8e29 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,9 +18,9 @@ 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!!) { - _collection = collection ?? throw new ArgumentNullException(nameof(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 cdfc29a7a3e43d..34f1b26c3d2104 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,11 +13,8 @@ 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!!) { - if (comparison == null) - throw new ArgumentNullException(nameof(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 ef35460a01327f..524fe11a4d9b32 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,13 +9,8 @@ internal sealed class ICollectionDebugView { private readonly ICollection _collection; - public ICollectionDebugView(ICollection collection) + public ICollectionDebugView(ICollection collection!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(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 c7e58780a2f751..3a564be99c17c9 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,11 +9,8 @@ internal sealed class IDictionaryDebugView where K : notnull { private readonly IDictionary _dict; - public IDictionaryDebugView(IDictionary dictionary) + public IDictionaryDebugView(IDictionary dictionary!!) { - if (dictionary == null) - throw new ArgumentNullException(nameof(dictionary)); - _dict = dictionary; } @@ -33,11 +30,8 @@ internal sealed class DictionaryKeyCollectionDebugView { private readonly ICollection _collection; - public DictionaryKeyCollectionDebugView(ICollection collection) + public DictionaryKeyCollectionDebugView(ICollection collection!!) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); - _collection = collection; } @@ -57,11 +51,8 @@ internal sealed class DictionaryValueCollectionDebugView { private readonly ICollection _collection; - public DictionaryValueCollectionDebugView(ICollection collection) + public DictionaryValueCollectionDebugView(ICollection collection!!) { - if (collection == null) - throw new ArgumentNullException(nameof(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 1953d9dd35ee1f..96424c17c89229 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,11 +49,8 @@ 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!!) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); - _array = EnumerableHelpers.ToArray(collection, out _size); if (_size != _array.Length) _tail = _size; } @@ -98,13 +95,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); @@ -127,13 +119,8 @@ public void CopyTo(T[] array, int arrayIndex) } } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 31ac94a0f48334..d0cd1fc26ff65f 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,13 +9,8 @@ internal sealed class QueueDebugView { private readonly Queue _queue; - public QueueDebugView(Queue queue) + public QueueDebugView(Queue queue!!) { - if (queue == null) - { - throw new ArgumentNullException(nameof(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 d311cd0c94bbde..e0fcbee7509ece 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs @@ -472,13 +472,8 @@ 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!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_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); @@ -631,11 +626,7 @@ public virtual object? this[object key] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } - + ArgumentNullException.ThrowIfNull(key); // Take a snapshot of buckets, in case another thread does a resize Bucket[] lbuckets = _buckets; @@ -837,13 +828,8 @@ 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) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } - if (_count >= _loadsize) { expand(); @@ -978,13 +964,8 @@ 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!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_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. @@ -1029,20 +1010,13 @@ 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!!) { - if (table == null) - throw new ArgumentNullException(nameof(table)); return new SyncHashtable(table); } - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) @@ -1203,10 +1177,8 @@ internal KeyCollection(Hashtable hashtable) _hashtable = hashtable; } - public void CopyTo(Array array, int arrayIndex) + public void CopyTo(Array array!!, int arrayIndex) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -1239,10 +1211,8 @@ internal ValueCollection(Hashtable hashtable) _hashtable = hashtable; } - public void CopyTo(Array array, int arrayIndex) + public void CopyTo(Array array!!, int arrayIndex) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (arrayIndex < 0) @@ -1327,12 +1297,8 @@ public override bool Contains(object key) return _table.Contains(key); } - public override bool ContainsKey(object key) + public override bool ContainsKey(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } return _table.ContainsKey(key); } @@ -1523,13 +1489,8 @@ internal sealed class HashtableDebugView { private readonly Hashtable _hashtable; - public HashtableDebugView(Hashtable hashtable) + public HashtableDebugView(Hashtable hashtable!!) { - if (hashtable == null) - { - throw new ArgumentNullException(nameof(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 b06c9edb249654..9189dd6c820f86 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ListDictionaryInternal.cs @@ -29,14 +29,10 @@ public ListDictionaryInternal() { } - public object? this[object key] + public object? this[object key!!] { get { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } DictionaryNode? node = head; while (node != null) @@ -51,11 +47,6 @@ public object? this[object key] } set { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } - version++; DictionaryNode? last = null; DictionaryNode? node; @@ -103,13 +94,8 @@ 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) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } - version++; DictionaryNode? last = null; for (DictionaryNode? node = head; node != null; node = node.next) @@ -143,12 +129,8 @@ public void Clear() version++; } - public bool Contains(object key) + public bool Contains(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } for (DictionaryNode? node = head; node != null; node = node.next) { if (node.key.Equals(key)) @@ -159,11 +141,8 @@ public bool Contains(object key) return false; } - public void CopyTo(Array array, int index) + public void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); @@ -190,12 +169,8 @@ IEnumerator IEnumerable.GetEnumerator() return new NodeEnumerator(this); } - public void Remove(object key) + public void Remove(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); - } version++; DictionaryNode? last = null; DictionaryNode? node; @@ -318,10 +293,8 @@ public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) this.isKeys = isKeys; } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(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 89af10ba7109f4..6b6016d68d7753 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,13 +7,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 57c6b4604dc1d8..9e0facdfa34b00 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,9 +20,9 @@ public class ReadOnlyDictionary : IDictionary, IDict [NonSerialized] private ValueCollection? _values; - public ReadOnlyDictionary(IDictionary dictionary) + public ReadOnlyDictionary(IDictionary dictionary!!) { - m_dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary)); + m_dictionary = dictionary; } protected IDictionary Dictionary => m_dictionary; @@ -105,13 +105,8 @@ IEnumerator IEnumerable.GetEnumerator() return ((IEnumerable)m_dictionary).GetEnumerator(); } - private static bool IsCompatibleKey(object key) + private static bool IsCompatibleKey(object key!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - return key is TKey; } @@ -254,9 +249,9 @@ public sealed class KeyCollection : ICollection, ICollection, IReadOnlyCol { private readonly ICollection _collection; - internal KeyCollection(ICollection collection) + internal KeyCollection(ICollection collection!!) { - _collection = collection ?? throw new ArgumentNullException(nameof(collection)); + _collection = collection; } void ICollection.Add(TKey item) @@ -308,9 +303,9 @@ public sealed class ValueCollection : ICollection, ICollection, IReadOnl { private readonly ICollection _collection; - internal ValueCollection(ICollection collection) + internal ValueCollection(ICollection collection!!) { - _collection = collection ?? throw new ArgumentNullException(nameof(collection)); + _collection = collection; } void ICollection.Add(TValue item) diff --git a/src/libraries/System.Private.CoreLib/src/System/Convert.cs b/src/libraries/System.Private.CoreLib/src/System/Convert.cs index 94b9160f7253a6..bf101862a870cd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Convert.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Convert.cs @@ -226,13 +226,9 @@ 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) { Debug.Assert(value != null, "[Convert.DefaultToType]value!=null"); - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } if (ReferenceEquals(value.GetType(), targetType)) { @@ -289,13 +285,8 @@ internal static object DefaultToType(IConvertible value, Type targetType, IForma } [return: NotNullIfNotNull("value")] - public static object? ChangeType(object? value, Type conversionType, IFormatProvider? provider) + public static object? ChangeType(object? value, Type conversionType!!, IFormatProvider? provider) { - if (conversionType is null) - { - throw new ArgumentNullException(nameof(conversionType)); - } - if (value == null) { if (conversionType.IsValueType) @@ -554,11 +545,8 @@ 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) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (value.Length != 1) throw new FormatException(SR.Format_NeedSingleChar); @@ -2309,21 +2297,13 @@ 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!!) { - if (inArray == null) - { - throw new ArgumentNullException(nameof(inArray)); - } return ToBase64String(new ReadOnlySpan(inArray), Base64FormattingOptions.None); } - public static string ToBase64String(byte[] inArray, Base64FormattingOptions options) + public static string ToBase64String(byte[] inArray!!, Base64FormattingOptions options) { - if (inArray == null) - { - throw new ArgumentNullException(nameof(inArray)); - } return ToBase64String(new ReadOnlySpan(inArray), options); } @@ -2332,10 +2312,8 @@ 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) { - if (inArray == null) - throw new ArgumentNullException(nameof(inArray)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); if (offset < 0) @@ -2379,13 +2357,8 @@ 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) { - // Do data verfication - if (inArray == null) - throw new ArgumentNullException(nameof(inArray)); - if (outArray == null) - throw new ArgumentNullException(nameof(outArray)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); if (offsetIn < 0) @@ -2709,11 +2682,8 @@ 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) { - if (inArray == null) - throw new ArgumentNullException(nameof(inArray)); - if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); @@ -2887,11 +2857,8 @@ 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!!) { - if (inArray == null) - throw new ArgumentNullException(nameof(inArray)); - return ToHexString(new ReadOnlySpan(inArray)); } @@ -2907,10 +2874,8 @@ 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) { - if (inArray == null) - throw new ArgumentNullException(nameof(inArray)); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index); 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 53a7b278fd2123..03ed33ceb1d5b7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -232,11 +232,8 @@ 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!!) { - if (calendar == null) - throw new ArgumentNullException(nameof(calendar)); - if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = calendar.ToDateTime(year, month, day, hour, minute, second, 0).UTicks; @@ -294,11 +291,8 @@ 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, int millisecond, Calendar calendar) + public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar!!) { - if (calendar == null) - throw new ArgumentNullException(nameof(calendar)); - if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = calendar.ToDateTime(year, month, day, hour, minute, second, millisecond).UTicks; @@ -311,10 +305,8 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, } } - 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) { - if (calendar == null) - throw new ArgumentNullException(nameof(calendar)); if ((uint)millisecond >= MillisPerSecond) ThrowMillisecondOutOfRange(); if ((uint)kind > (uint)DateTimeKind.Local) ThrowInvalidKind(); diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs index d0778363fb34f1..651fb25b544e15 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs @@ -470,24 +470,14 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) { - if (info == null) - { - throw new ArgumentNullException(nameof(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 c46fe5094cb32d..b5de5cff5f0236 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Decimal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Decimal.cs @@ -182,21 +182,15 @@ public Decimal(double value) DecCalc.VarDecFromR8(value, out AsMutable(ref this)); } - private Decimal(SerializationInfo info, StreamingContext context) + private Decimal(SerializationInfo info!!, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(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) { - if (info == null) - throw new ArgumentNullException(nameof(info)); - // Serialize both the old and the new format info.AddValue("flags", _flags); info.AddValue("hi", (int)High); diff --git a/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs b/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs index 1290a00f59c51e..2ca3e6a84020f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs @@ -432,13 +432,8 @@ 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) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - int i; // Find the method that match... int CurIdx = 0; @@ -773,11 +768,8 @@ 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, ParameterModifier[]? modifiers) + public static MethodBase? ExactBinding(MethodBase[] match!!, Type[] types, ParameterModifier[]? modifiers) { - if (match == null) - throw new ArgumentNullException(nameof(match)); - MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; @@ -816,11 +808,8 @@ 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, ParameterModifier[]? modifiers) + public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match!!, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { - if (match == null) - throw new ArgumentNullException(nameof(match)); - PropertyInfo? bestMatch = null; 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 fd347add1795d9..bd4852c036593a 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 @@ -517,8 +517,7 @@ public static bool ForAll(int fromInclusive, int toExclusive, Predicate pre { if (fromInclusive > toExclusive) throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); + ArgumentNullException.ThrowIfNull(predicate); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; @@ -536,13 +535,8 @@ 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!!) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); - foreach (T t in collection) if (!predicate(t)) return false; return true; @@ -567,8 +561,7 @@ public static bool Exists(int fromInclusive, int toExclusive, Predicate pre { if (fromInclusive > toExclusive) throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); - if (predicate == null) - throw new ArgumentNullException(nameof(predicate)); + ArgumentNullException.ThrowIfNull(predicate); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; @@ -585,13 +578,8 @@ 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!!) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); - if (predicate == null) - throw new ArgumentNullException(nameof(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 d617c14fcca152..802410712c07d5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs @@ -19,11 +19,8 @@ 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!!) { - if (provider == null) - throw new ArgumentNullException(nameof(provider)); - return Interlocked.Exchange(ref s_provider, provider); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs index ea67b9c043afd1..65b2e6589e05fb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerDisplayAttribute.cs @@ -35,10 +35,7 @@ public Type? Target get => _target; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); TargetTypeName = value.AssemblyQualifiedName; _target = value; 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 1f99516869be62..982c462535f0c3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerTypeProxyAttribute.cs @@ -11,13 +11,8 @@ public sealed class DebuggerTypeProxyAttribute : Attribute private Type? _target; public DebuggerTypeProxyAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - ProxyTypeName = type.AssemblyQualifiedName!; } @@ -37,10 +32,7 @@ public Type? Target get => _target; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); TargetTypeName = value.AssemblyQualifiedName; _target = value; 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 425156d948936a..1b011101a2f757 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebuggerVisualizerAttribute.cs @@ -30,54 +30,30 @@ public DebuggerVisualizerAttribute( public DebuggerVisualizerAttribute( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string visualizerTypeName, - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizerObjectSource) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizerObjectSource!!) { - if (visualizerObjectSource == null) - { - throw new ArgumentNullException(nameof(visualizerObjectSource)); - } - VisualizerTypeName = visualizerTypeName; VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer) + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer!!) { - if (visualizer == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (visualizer == null) - { - throw new ArgumentNullException(nameof(visualizer)); - } - if (visualizerObjectSource == null) - { - throw new ArgumentNullException(nameof(visualizerObjectSource)); - } - VisualizerTypeName = visualizer.AssemblyQualifiedName!; VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName; } public DebuggerVisualizerAttribute( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type visualizer!!, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] string? visualizerObjectSourceTypeName) { - if (visualizer == null) - { - throw new ArgumentNullException(nameof(visualizer)); - } - VisualizerTypeName = visualizer.AssemblyQualifiedName!; VisualizerObjectSourceTypeName = visualizerObjectSourceTypeName; } @@ -95,10 +71,7 @@ public Type? Target get => _target; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); TargetTypeName = value.AssemblyQualifiedName; _target = value; 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 52472948bfee2b..c86c3be39fe76e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs @@ -76,22 +76,16 @@ public StackTrace(int skipFrames, bool fNeedFileInfo) /// /// Constructs a stack trace from the current location. /// - public StackTrace(Exception e) + public StackTrace(Exception e!!) { - if (e == null) - throw new ArgumentNullException(nameof(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) { - if (e == null) - throw new ArgumentNullException(nameof(e)); - InitializeForException(e, METHODS_TO_SKIP, fNeedFileInfo); } @@ -99,11 +93,8 @@ 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) { - if (e == null) - throw new ArgumentNullException(nameof(e)); - if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -115,11 +106,8 @@ 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) { - if (e == null) - throw new ArgumentNullException(nameof(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 0c23cf99222b2c..2c605cd8ee48a1 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 @@ -29,22 +29,12 @@ public abstract class DiagnosticCounter : IDisposable /// All Counters live as long as the EventSource that they are attached to unless they are /// explicitly Disposed. /// - /// The name. - /// The event source. - internal DiagnosticCounter(string name, EventSource eventSource) + /// The name. + /// The event source. + internal DiagnosticCounter(string Name!!, EventSource EventSource!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(Name)); - } - - if (eventSource == null) - { - throw new ArgumentNullException(nameof(EventSource)); - } - - Name = name; - EventSource = eventSource; + this.Name = Name; + this.EventSource = 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 b54a5a50ba62ed..2124c8b71a7590 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 @@ -466,8 +466,10 @@ public static void SendCommand(EventSource eventSource, EventCommand command, ID return; } - if (eventSource == null) + if (eventSource is null) + { throw new ArgumentNullException(nameof(eventSource)); + } // User-defined EventCommands should not conflict with the reserved commands. if ((int)command <= (int)EventCommand.Update && (int)command != (int)EventCommand.SendManifest) @@ -4173,13 +4175,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(eventSource)); - } - eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments); #if FEATURE_PERFTRACING @@ -4194,13 +4191,8 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword /// /// This call never has an effect on other EventListeners. /// - public void DisableEvents(EventSource eventSource) + public void DisableEvents(EventSource eventSource!!) { - if (eventSource == 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 86d46a040faa50..a06de9bb623a1e 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,11 +35,8 @@ 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 == 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 ed9697d2450229..e2849498a674a4 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,11 +33,8 @@ 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 == 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 98cd97f567a5e5..fa09bfa8db3260 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,11 +75,8 @@ public bool Contains(KeyValuePair entry) return ContainsKey(entry.Key); } - public bool ContainsKey(string key) + public bool ContainsKey(string key!!) { - if (key == null) - throw new System.ArgumentNullException(nameof(key)); - foreach (string item in m_names) { if (item == key) @@ -121,11 +118,8 @@ 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 == null) - throw new System.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 b6b739f3eeeb50..52ee741b94c535 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,18 +86,14 @@ 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( - eventSourceName == null ? default : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), + GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName!, config, traits) { - if (eventSourceName == null) - { - throw new ArgumentNullException(nameof(eventSourceName)); - } } /// 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 c8367baf80f96b..5716d3b6bbac2f 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,15 +89,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } - this.typeInfos = MakeArray(paramInfos); #if FEATURE_PERFTRACING this.paramNames = MakeParamNameArray(paramInfos); @@ -129,14 +124,9 @@ internal TraceLoggingEventTypes( private TraceLoggingEventTypes( EventTags tags, - string defaultName, + string defaultName!!, TraceLoggingTypeInfo[] typeInfos) { - if (defaultName == null) - { - throw new ArgumentNullException(nameof(defaultName)); - } - this.typeInfos = typeInfos; this.name = defaultName; this.tags = tags; @@ -189,13 +179,8 @@ 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 == 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) @@ -209,13 +194,8 @@ 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 == 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++) @@ -227,13 +207,8 @@ private static TraceLoggingTypeInfo[] MakeArray(Type[] types) } private static TraceLoggingTypeInfo[] MakeArray( - TraceLoggingTypeInfo[] typeInfos) + TraceLoggingTypeInfo[] typeInfos!!) { - if (typeInfos == 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 8a699e243fc379..ad1f46b6b19142 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,36 +27,21 @@ internal abstract class TraceLoggingTypeInfo private readonly Type dataType; private readonly Func propertyValueFactory; - internal TraceLoggingTypeInfo(Type dataType) + internal TraceLoggingTypeInfo(Type dataType!!) { - if (dataType == 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 == null) - { - throw new ArgumentNullException(nameof(dataType)); - } - - if (name == 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 7267c82a7449ce..b319dfc6e6a224 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Enum.cs @@ -286,22 +286,16 @@ 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) + public static string? GetName(Type enumType!!, object value) { - if (enumType is null) - throw new ArgumentNullException(nameof(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) + public static string[] GetNames(Type enumType!!) { - if (enumType is null) - throw new ArgumentNullException(nameof(enumType)); - return enumType.GetEnumNames(); } @@ -325,19 +319,14 @@ 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) + public static Array GetValues(Type enumType!!) { - if (enumType is null) - throw new ArgumentNullException(nameof(enumType)); - return enumType.GetEnumValues(); } [Intrinsic] - public bool HasFlag(Enum flag) + public bool HasFlag(Enum flag!!) { - if (flag is null) - throw new ArgumentNullException(nameof(flag)); if (GetType() != flag.GetType() && !GetType().IsEquivalentTo(flag.GetType())) throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), GetType())); @@ -418,11 +407,8 @@ 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) { - if (enumType is null) - throw new ArgumentNullException(nameof(enumType)); - return enumType.IsEnumDefined(value); } @@ -1022,11 +1008,8 @@ 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!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); @@ -1046,16 +1029,10 @@ public static object ToObject(Type enumType, object value) }; } - public static string Format(Type enumType, object value, string format) + public static string Format(Type enumType, object value!!, string format!!) { RuntimeType rtType = ValidateRuntimeType(enumType); - if (value == null) - throw new ArgumentNullException(nameof(value)); - - if (format == null) - throw new ArgumentNullException(nameof(format)); - // If the value is an Enum then we need to extract the underlying value from it Type valueType = value.GetType(); if (valueType.IsEnum) diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.cs index 414db07d199e64..b3b011ac005dbf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.cs @@ -21,11 +21,8 @@ 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!!) { - if (variable == null) - throw new ArgumentNullException(nameof(variable)); - return GetEnvironmentVariableCore(variable); } @@ -34,8 +31,7 @@ public static partial class Environment if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariable(variable); - if (variable == null) - throw new ArgumentNullException(nameof(variable)); + ArgumentNullException.ThrowIfNull(variable); bool fromMachine = ValidateAndConvertRegistryTarget(target); return GetEnvironmentVariableFromRegistry(variable, fromMachine); @@ -82,11 +78,8 @@ public static string CurrentDirectory } } - public static string ExpandEnvironmentVariables(string name) + public static string ExpandEnvironmentVariables(string name!!) { - if (name == null) - throw new ArgumentNullException(nameof(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 a6760916f93061..8196ecc7e0fc57 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Exception.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Exception.cs @@ -37,11 +37,8 @@ public Exception(string? message, Exception? innerException) _innerException = innerException; } - protected Exception(SerializationInfo info, StreamingContext context) + protected Exception(SerializationInfo info!!, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(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,17 +90,9 @@ public virtual string? Source set => _source = value; } - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) + public virtual void GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - if (_source == null) - { - _source = Source; // Set the Source information correctly before serialization - } + _source ??= Source; // Set the Source information correctly before serialization info.AddValue("ClassName", GetClassName(), typeof(string)); // Do not rename (binary serialization) info.AddValue("Message", _message, 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 6624b50c2953a4..6013b99da11d9d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/FormattableString.cs +++ b/src/libraries/System.Private.CoreLib/src/System/FormattableString.cs @@ -44,10 +44,8 @@ public abstract class FormattableString : IFormattable /// public abstract string ToString(IFormatProvider? formatProvider); - string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) - { - return ToString(formatProvider); - } + string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) => + ToString(formatProvider); /// /// Format the given object in the invariant culture. This static method may be @@ -62,15 +60,8 @@ string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) /// Invariant($"{{ lat = {latitude}; lon = {longitude} }}") /// /// - public static string Invariant(FormattableString formattable) - { - if (formattable == null) - { - throw new ArgumentNullException(nameof(formattable)); - } - - return formattable.ToString(Globalization.CultureInfo.InvariantCulture); - } + public static string Invariant(FormattableString formattable!!) => + formattable.ToString(Globalization.CultureInfo.InvariantCulture); /// /// Format the given object in the current culture. This static method may be @@ -85,19 +76,10 @@ public static string Invariant(FormattableString formattable) /// CurrentCulture($"{{ lat = {latitude}; lon = {longitude} }}") /// /// - public static string CurrentCulture(FormattableString formattable) - { - if (formattable == null) - { - throw new ArgumentNullException(nameof(formattable)); - } - - return formattable.ToString(Globalization.CultureInfo.CurrentCulture); - } + public static string CurrentCulture(FormattableString formattable!!) => + formattable.ToString(Globalization.CultureInfo.CurrentCulture); - public override string ToString() - { - return 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 5daaf13004675c..4faea9c957d0d9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/Calendar.cs @@ -82,12 +82,8 @@ public virtual object Clone() return o; } - public static Calendar ReadOnly(Calendar calendar) + public static Calendar ReadOnly(Calendar calendar!!) { - if (calendar == null) - { - throw new ArgumentNullException(nameof(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 02c846c457beea..58c81836dc762a 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 @@ -613,13 +613,11 @@ private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan source, ReadOnlySpa } } - private unsafe SortKey IcuCreateSortKey(string source, CompareOptions options) + private unsafe SortKey IcuCreateSortKey(string source!!, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); - if (source==null) { throw new ArgumentNullException(nameof(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.Invariant.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.Invariant.cs index c3d568002907b6..0de506a38d3b4f 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,10 +9,8 @@ namespace System.Globalization { public partial class CompareInfo { - private SortKey InvariantCreateSortKey(string source, CompareOptions options) + private SortKey InvariantCreateSortKey(string source!!, CompareOptions options) { - if (source == null) { throw new ArgumentNullException(nameof(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 1dc301b970aa5f..379a98b97fd2c6 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,13 +366,11 @@ 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) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(GlobalizationMode.UseNls); - if (source == null) { throw new ArgumentNullException(nameof(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.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs index bf68d1214d3616..1bf3346472d957 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CompareInfo.cs @@ -62,13 +62,9 @@ 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!!) { // Parameter checking. - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib, nameof(assembly)); @@ -82,16 +78,8 @@ 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!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib, nameof(assembly)); @@ -117,13 +105,8 @@ 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!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - return CultureInfo.GetCultureInfo(name).CompareInfo; } @@ -132,13 +115,8 @@ public static bool IsSortable(char ch) return IsSortable(MemoryMarshal.CreateReadOnlySpan(ref ch, 1)); } - public static bool IsSortable(string text) + public static bool IsSortable(string text!!) { - if (text == null) - { - throw new ArgumentNullException(nameof(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 baf1e6dd215017..cf9ed8ce941def 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -164,13 +164,8 @@ public CultureInfo(string name) : this(name, true) { } - public CultureInfo(string name, bool useUserOverride) + public CultureInfo(string name!!, bool useUserOverride) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - // Get our data providing record CultureData? cultureData = CultureData.GetCultureData(name, useUserOverride); @@ -243,13 +238,8 @@ 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!!) { - if (cultureName == null) - { - throw new ArgumentNullException(nameof(cultureName), SR.ArgumentNull_String); - } - CultureData? cultureData = CultureData.GetCultureData(cultureName, false) ?? throw new CultureNotFoundException(nameof(cultureName), cultureName, GetCultureNotSupportedExceptionMessage()); @@ -420,10 +410,7 @@ public static CultureInfo CurrentUICulture } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); CultureInfo.VerifyCultureName(value, true); @@ -750,10 +737,7 @@ public virtual NumberFormatInfo NumberFormat } set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _numInfo = value; @@ -780,10 +764,7 @@ public virtual DateTimeFormatInfo DateTimeFormat set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _dateTimeInfo = value; @@ -971,13 +952,8 @@ public virtual object Clone() return ci; } - public static CultureInfo ReadOnly(CultureInfo ci) + public static CultureInfo ReadOnly(CultureInfo ci!!) { - if (ci == null) - { - throw new ArgumentNullException(nameof(ci)); - } - if (ci.IsReadOnly) { return ci; @@ -1083,14 +1059,8 @@ 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!!) { - // Make sure we have a valid, non-zero length string as name - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - name = CultureData.AnsiToLower(name); Dictionary nameTable = CachedCulturesByName; CultureInfo? result; @@ -1123,17 +1093,8 @@ 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!!) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - if (altName is null) - { - throw new ArgumentNullException(nameof(altName)); - } - name = CultureData.AnsiToLower(name); altName = CultureData.AnsiToLower(altName); string nameAndAltName = name + "\xfffd" + altName; @@ -1168,13 +1129,8 @@ 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) { - if (name is null) - { - throw new ArgumentNullException(nameof(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 b4c44b86800614..77f18189633022 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs @@ -372,10 +372,7 @@ public string AMDesignator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); ClearTokenHashTable(); amDesignator = value; @@ -396,10 +393,7 @@ public Calendar Calendar { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value == calendar) { @@ -482,13 +476,8 @@ public Calendar Calendar /// /// Get the era value by parsing the name of the era. /// - public int GetEra(string eraName) + public int GetEra(string eraName!!) { - if (eraName == null) - { - throw new ArgumentNullException(nameof(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 @@ -621,10 +610,7 @@ public string DateSeparator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); ClearTokenHashTable(); dateSeparator = value; @@ -701,10 +687,7 @@ public string FullDateTimePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); fullDateTimePattern = value; } @@ -725,10 +708,7 @@ public string LongDatePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Remember the new string longDatePattern = value; @@ -762,10 +742,7 @@ public string LongTimePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Remember the new string longTimePattern = value; @@ -807,10 +784,7 @@ public string MonthDayPattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); monthDayPattern = value; } @@ -834,10 +808,7 @@ public string PMDesignator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); ClearTokenHashTable(); pmDesignator = value; @@ -865,10 +836,7 @@ public string ShortDatePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Remember the new string shortDatePattern = value; @@ -904,10 +872,7 @@ public string ShortTimePattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Remember the new string shortTimePattern = value; @@ -1021,10 +986,7 @@ public string TimeSeparator { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); ClearTokenHashTable(); timeSeparator = value; @@ -1049,10 +1011,7 @@ public string YearMonthPattern { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // Remember the new string yearMonthPattern = value; @@ -1092,10 +1051,7 @@ public string[] AbbreviatedDayNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 7) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value)); @@ -1120,10 +1076,7 @@ public string[] ShortestDayNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 7) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value)); @@ -1143,10 +1096,7 @@ public string[] DayNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 7) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), nameof(value)); @@ -1168,10 +1118,7 @@ public string[] AbbreviatedMonthNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); @@ -1192,10 +1139,7 @@ public string[] MonthNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); @@ -1639,13 +1583,8 @@ private string[] UnclonedLongTimePatterns } } - public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) + public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi!!) { - if (dtfi == null) - { - throw new ArgumentNullException(nameof(dtfi)); - } - if (dtfi.IsReadOnly) { return dtfi; @@ -1694,10 +1633,7 @@ public void SetAllDateTimePatterns(string[] patterns, char format) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (patterns == null) - { - throw new ArgumentNullException(nameof(patterns)); - } + ArgumentNullException.ThrowIfNull(patterns); if (patterns.Length == 0) { @@ -1760,10 +1696,7 @@ public string[] AbbreviatedMonthGenitiveNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); @@ -1784,10 +1717,7 @@ public string[] MonthGenitiveNames { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), nameof(value)); 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 8e2ee3d3af8acd..919f0cf7cc486c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/GlobalizationExtensions.cs @@ -5,13 +5,8 @@ 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) { - if (compareInfo == null) - { - throw new ArgumentNullException(nameof(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 81b20d53e55a48..6b5a7b64c9ed87 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/IdnMapping.cs @@ -56,17 +56,13 @@ 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) { - if (unicode == null) - throw new ArgumentNullException(nameof(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) { - if (unicode == null) - throw new ArgumentNullException(nameof(unicode)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > unicode.Length) @@ -103,17 +99,13 @@ 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) { - if (ascii == null) - throw new ArgumentNullException(nameof(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) { - if (ascii == null) - throw new ArgumentNullException(nameof(ascii)); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (index > ascii.Length) @@ -438,7 +430,7 @@ private static string PunycodeEncode(string unicode) /* handled already. Find the next larger one: */ int j; int m; - int test = 0; + int test; for (m = c_maxint, j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1) 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 8387dd024d17fd..fa8b8ab2680b97 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs @@ -80,13 +80,8 @@ public NumberFormatInfo() { } - private static void VerifyNativeDigits(string[] nativeDig, string propertyName) + private static void VerifyNativeDigits(string[] nativeDig!!, string propertyName) { - if (nativeDig == null) - { - throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array); - } - if (nativeDig.Length != 10) { throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName); @@ -280,10 +275,7 @@ public int[] CurrencyGroupSizes get => (int[])_currencyGroupSizes.Clone(); set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); @@ -298,10 +290,7 @@ public int[] NumberGroupSizes get => (int[])_numberGroupSizes.Clone(); set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); @@ -316,10 +305,7 @@ public int[] PercentGroupSizes get => (int[])_percentGroupSizes.Clone(); set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); int[] inputSizes = (int[])value.Clone(); @@ -344,10 +330,7 @@ public string CurrencySymbol get => _currencySymbol; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _currencySymbol = value; @@ -381,10 +364,7 @@ public string NaNSymbol get => _nanSymbol; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _nanSymbol = value; @@ -471,10 +451,7 @@ public string NegativeInfinitySymbol get => _negativeInfinitySymbol; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _negativeInfinitySymbol = value; @@ -486,10 +463,7 @@ public string NegativeSign get => _negativeSign; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _negativeSign = value; @@ -560,10 +534,7 @@ public string PositiveInfinitySymbol get => _positiveInfinitySymbol; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _positiveInfinitySymbol = value; @@ -575,10 +546,7 @@ public string PositiveSign get => _positiveSign; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _positiveSign = value; @@ -642,10 +610,7 @@ public string PerMilleSymbol get => _perMilleSymbol; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _perMilleSymbol = value; @@ -679,13 +644,8 @@ public DigitShapes DigitSubstitution return formatType == typeof(NumberFormatInfo) ? this : null; } - public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) + public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi!!) { - if (nfi == null) - { - throw new ArgumentNullException(nameof(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 addd8a0a667851..41beb5951e7440 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/RegionInfo.cs @@ -23,13 +23,8 @@ public class RegionInfo // The RegionInfo for our current region internal static volatile RegionInfo? s_currentRegionInfo; - public RegionInfo(string name) + public RegionInfo(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(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 a98b7b880d1fda..231a4594608b8a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/SortKey.cs @@ -43,17 +43,8 @@ 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!!) { - if (sortkey1 == null) - { - throw new ArgumentNullException(nameof(sortkey1)); - } - if (sortkey2 == null) - { - throw new ArgumentNullException(nameof(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 4679beebb4a484..a0b71e7c6188f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -90,13 +90,8 @@ 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!!) { - if (textInfo == null) - { - throw new ArgumentNullException(nameof(textInfo)); - } - if (textInfo.IsReadOnly) { return textInfo; @@ -128,10 +123,7 @@ public string ListSeparator get => _listSeparator ??= _cultureData.ListSeparator; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); VerifyWritable(); _listSeparator = value; @@ -172,13 +164,8 @@ internal static char ToLowerInvariant(char c) return Invariant.ChangeCase(c, toUpper: false); } - public string ToLower(string str) + public string ToLower(string str!!) { - if (str == null) - { - throw new ArgumentNullException(nameof(str)); - } - if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToLower(str); @@ -586,13 +573,8 @@ internal static char ToUpperInvariant(char c) return Invariant.ChangeCase(c, toUpper: true); } - public string ToUpper(string str) + public string ToUpper(string str!!) { - if (str == null) - { - throw new ArgumentNullException(nameof(str)); - } - if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToUpper(str); @@ -664,13 +646,8 @@ 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!!) { - if (str == null) - { - throw new ArgumentNullException(nameof(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 a5ba1f6c870b20..590ee4c396be42 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Guid.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Guid.cs @@ -91,12 +91,8 @@ 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!!) { - if (d == null) - { - throw new ArgumentNullException(nameof(d)); - } if (d.Length != 8) { throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d)); @@ -213,13 +209,8 @@ 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!!) { - if (g == null) - { - throw new ArgumentNullException(nameof(g)); - } - var result = new GuidResult(GuidParseThrowStyle.All); bool success = TryParseGuid(g, ref result); Debug.Assert(success, "GuidParseThrowStyle.All means throw on all failures"); 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 cea8148a7d9186..a9e94ca5bce630 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryReader.cs @@ -45,16 +45,8 @@ 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } if (!input.CanRead) { throw new ArgumentException(SR.Argument_StreamNotReadable); @@ -317,12 +309,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -449,12 +437,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 a9cd6bd1575893..f81b64c4dd2160 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs @@ -42,12 +42,8 @@ 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) { - if (output == null) - throw new ArgumentNullException(nameof(output)); - if (encoding == null) - throw new ArgumentNullException(nameof(encoding)); if (!output.CanWrite) throw new ArgumentException(SR.Argument_StreamNotWritable); @@ -154,10 +150,8 @@ 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!!) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); OutStream.Write(buffer, 0, buffer.Length); } @@ -215,11 +209,8 @@ 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!!) { - if (chars == null) - throw new ArgumentNullException(nameof(chars)); - WriteCharsCommonWithoutLengthPrefix(chars, useThisWriteOverride: false); } @@ -228,10 +219,8 @@ 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) { - if (chars == null) - throw new ArgumentNullException(nameof(chars)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -347,11 +336,8 @@ 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!!) { - if (value == null) - throw new ArgumentNullException(nameof(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 5d6a274fed1eff..c23e466380a5fc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Directory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Directory.cs @@ -152,16 +152,11 @@ 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) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - if (searchPattern == null) - throw new ArgumentNullException(nameof(searchPattern)); - FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType); return searchTarget switch @@ -206,11 +201,8 @@ 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!!) { - if (path == null) - throw new ArgumentNullException(nameof(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 c367db63d3905f..f412243f097a2a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/DirectoryInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/DirectoryInfo.cs @@ -25,9 +25,9 @@ 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) { - OriginalPath = originalPath ?? throw new ArgumentNullException(nameof(originalPath)); + OriginalPath = originalPath; fullPath = fullPath ?? originalPath; fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath); @@ -55,10 +55,8 @@ public DirectoryInfo? Parent } } - public DirectoryInfo CreateSubdirectory(string path) + public DirectoryInfo CreateSubdirectory(string path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); if (Path.IsPathRooted(path)) @@ -165,13 +163,11 @@ public IEnumerable EnumerateFileSystemInfos(string searchPattern private IEnumerable InternalEnumerateInfos( string path, - string searchPattern, + string searchPattern!!, SearchTarget searchTarget, EnumerationOptions options) { Debug.Assert(path != null); - if (searchPattern == null) - throw new ArgumentNullException(nameof(searchPattern)); _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 3f2e5a3b324ad4..f15399452c5958 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,10 +23,10 @@ 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) { - _directory = directory ?? throw new ArgumentNullException(nameof(directory)); - _transform = transform ?? throw new ArgumentNullException(nameof(transform)); + _directory = directory; + _transform = transform; _options = options ?? EnumerationOptions.Default; // We need to create the enumerator up front to ensure that we throw I/O exceptions for 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 6f22a9729b5d02..536cb8c41748fd 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,9 +28,9 @@ 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) { - _originalRootDirectory = directory ?? throw new ArgumentNullException(nameof(directory)); + _originalRootDirectory = directory; string path = isNormalized ? directory : Path.GetFullPath(directory); _rootDirectory = Path.TrimEndingDirectorySeparator(path); 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 d8b1124ed9b1b9..0be224c3b7fb54 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs @@ -334,10 +334,7 @@ public static void WriteAllLines(string path, string[] contents, Encoding encodi public static void WriteAllLines(string path, IEnumerable contents, Encoding encoding) { Validate(path, encoding); - - if (contents == null) - throw new ArgumentNullException(nameof(contents)); - + ArgumentNullException.ThrowIfNull(contents); InternalWriteAllLines(new StreamWriter(path, false, encoding), contents); } @@ -371,23 +368,15 @@ public static void AppendAllLines(string path, IEnumerable contents) public static void AppendAllLines(string path, IEnumerable contents, Encoding encoding) { Validate(path, encoding); - - if (contents == null) - throw new ArgumentNullException(nameof(contents)); - + ArgumentNullException.ThrowIfNull(contents); InternalWriteAllLines(new StreamWriter(path, true, encoding), contents); } 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) { - if (sourceFileName == null) - throw new ArgumentNullException(nameof(sourceFileName)); - if (destinationFileName == null) - throw new ArgumentNullException(nameof(destinationFileName)); - FileSystem.ReplaceFile( Path.GetFullPath(sourceFileName), Path.GetFullPath(destinationFileName), @@ -645,10 +634,7 @@ private static async Task InternalReadAllLinesAsync(string path, Encod public static Task WriteAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { Validate(path, encoding); - - if (contents == null) - throw new ArgumentNullException(nameof(contents)); - + ArgumentNullException.ThrowIfNull(contents); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: false), contents, cancellationToken); @@ -693,10 +679,7 @@ private static async Task InternalWriteAllLinesAsync(TextWriter writer, IEnumera public static Task AppendAllLinesAsync(string path, IEnumerable contents, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken)) { Validate(path, encoding); - - if (contents == null) - throw new ArgumentNullException(nameof(contents)); - + ArgumentNullException.ThrowIfNull(contents); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : InternalWriteAllLinesAsync(AsyncStreamWriter(path, encoding, append: true), contents, cancellationToken); 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 0d9db030f900dd..27224f10f93204 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileInfo.cs @@ -163,11 +163,8 @@ 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) { - if (destinationFileName == null) - throw new ArgumentNullException(nameof(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 77685bb3b9a6a5..5e6314cf525d8a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStream.cs @@ -520,13 +520,8 @@ 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!!) { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(asyncResult)); - } - return _strategy.EndRead(asyncResult); } @@ -546,13 +541,8 @@ 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!!) { - if (asyncResult == null) - { - throw new ArgumentNullException(nameof(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 0c1739873f4031..76da4438b2d4ce 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs @@ -59,11 +59,8 @@ public MemoryStream(byte[] buffer) { } - public MemoryStream(byte[] buffer, bool writable) + public MemoryStream(byte[] buffer!!, bool writable) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; @@ -80,10 +77,8 @@ 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) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) 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 655a70719b845e..1b4f0119202024 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,11 +38,8 @@ 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!!) { - if (path == null) - throw new ArgumentNullException(nameof(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)); @@ -56,14 +53,8 @@ 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!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - - if (basePath == null) - throw new ArgumentNullException(nameof(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 da52cdfd81e024..8ffb8321c92664 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs @@ -303,11 +303,8 @@ public static unsafe string GetRandomFileName() /// /// Thrown if is null. /// - public static bool IsPathFullyQualified(string path) + public static bool IsPathFullyQualified(string path!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - return IsPathFullyQualified(path.AsSpan()); } @@ -368,13 +365,8 @@ public static string Combine(string path1, string path2, string path3, string pa return CombineInternal(path1, path2, path3, path4); } - public static string Combine(params string[] paths) + public static string Combine(params string[] paths!!) { - if (paths == null) - { - throw new ArgumentNullException(nameof(paths)); - } - int maxSize = 0; int firstComponent = 0; @@ -383,10 +375,7 @@ public static string Combine(params string[] paths) for (int i = 0; i < paths.Length; i++) { - if (paths[i] == null) - { - throw new ArgumentNullException(nameof(paths)); - } + ArgumentNullException.ThrowIfNull(paths[i], nameof(paths)); if (paths[i].Length == 0) { @@ -496,13 +485,8 @@ 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!!) { - if (paths == null) - { - throw new ArgumentNullException(nameof(paths)); - } - if (paths.Length == 0) { return string.Empty; @@ -867,17 +851,10 @@ 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) { - if (relativeTo == null) - throw new ArgumentNullException(nameof(relativeTo)); - if (PathInternal.IsEffectivelyEmpty(relativeTo.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(relativeTo)); - - if (path == null) - throw new ArgumentNullException(nameof(path)); - if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); 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 49bc2272d6c029..d7f6324bc2a981 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs @@ -763,13 +763,8 @@ 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) { - 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/System.Private.CoreLib/src/System/IO/StreamReader.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs index 785e2c8e4a0b6f..2d3db53b3d77b5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamReader.cs @@ -344,12 +344,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -427,12 +423,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -1006,12 +998,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -1229,12 +1217,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 656739a7c855e7..90cbe2f74464e6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs @@ -367,12 +367,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -700,12 +696,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -860,12 +852,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 a8e07ad382d151..8ea5f1083f2331 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringReader.cs @@ -83,12 +83,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -292,12 +288,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -314,12 +306,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 080d7716e98bb9..1213573f6bb5fb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs @@ -35,13 +35,8 @@ public StringWriter(StringBuilder sb) : this(sb, CultureInfo.CurrentCulture) { } - public StringWriter(StringBuilder sb, IFormatProvider? formatProvider) : base(formatProvider) + public StringWriter(StringBuilder sb!!, IFormatProvider? formatProvider) : base(formatProvider) { - if (sb == null) - { - throw new ArgumentNullException(nameof(sb), SR.ArgumentNull_Buffer); - } - _sb = sb; _isOpen = true; } @@ -98,12 +93,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 a0536bd022e8ee..299103cf093eb0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextReader.cs @@ -67,12 +67,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -265,12 +261,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -299,12 +291,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -339,11 +327,8 @@ internal async ValueTask ReadBlockAsyncInternal(Memory buffer, Cancel } #endregion - public static TextReader Synchronized(TextReader reader) + public static TextReader Synchronized(TextReader reader!!) { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); - return reader is SyncTextReader ? reader : new SyncTextReader(reader); } @@ -404,10 +389,8 @@ 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) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) @@ -417,10 +400,8 @@ 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) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_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 3468c535df03ee..27658be661f71a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/TextWriter.cs @@ -144,12 +144,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -702,11 +698,8 @@ public override void Write(char value) } } - public static TextWriter Synchronized(TextWriter writer) + public static TextWriter Synchronized(TextWriter writer!!) { - if (writer == null) - throw new ArgumentNullException(nameof(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 78d0dab488a565..110abad93168c8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -45,12 +45,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -329,12 +325,8 @@ 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 { - if (array == null) - { - throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); - } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -569,12 +561,8 @@ 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 { - if (array == null) - { - throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); - } 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 47b190dde4b49b..11a2727310919e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs @@ -82,12 +82,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -161,10 +157,8 @@ 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) { - if (pointer == null) - throw new ArgumentNullException(nameof(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 b1adbb1c022c45..416566055ddbb9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -138,12 +138,8 @@ 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) { - // The parameter checks must be in sync with the base version: - if (destination == null) - throw new ArgumentNullException(nameof(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 355578395db40d..843c17ea6c3083 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IntPtr.cs @@ -75,11 +75,8 @@ 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) { - if (info == null) - throw new ArgumentNullException(nameof(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 f5b55e491352e0..d3e93f2fd78499 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs @@ -62,12 +62,8 @@ public static class WebUtility return sb.ToString(); } - public static void HtmlEncode(string? value, TextWriter output) + public static void HtmlEncode(string? value, TextWriter output!!) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } if (string.IsNullOrEmpty(value)) { output.Write(value); @@ -205,13 +201,8 @@ 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!!) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - if (string.IsNullOrEmpty(value)) { output.Write(value); @@ -697,10 +688,7 @@ private static bool ValidateUrlEncodingParameters(byte[]? bytes, int offset, int { if (bytes == null && count == 0) return false; - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes)); - } + ArgumentNullException.ThrowIfNull(bytes); if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); diff --git a/src/libraries/System.Private.CoreLib/src/System/Nullable.cs b/src/libraries/System.Private.CoreLib/src/System/Nullable.cs index 089f970057dc8a..9f83fbe6a9f46c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Nullable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Nullable.cs @@ -97,13 +97,8 @@ 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!!) { - if (nullableType is null) - { - throw new ArgumentNullException(nameof(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 ce70c49dfc1471..c1d63f8a3bfa38 100644 --- a/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs +++ b/src/libraries/System.Private.CoreLib/src/System/OperatingSystem.cs @@ -29,10 +29,7 @@ internal OperatingSystem(PlatformID platform, Version version, string? servicePa throw new ArgumentOutOfRangeException(nameof(platform), platform, SR.Format(SR.Arg_EnumIllegalVal, platform)); } - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } + ArgumentNullException.ThrowIfNull(version); _platform = platform; _version = version; @@ -90,13 +87,8 @@ 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!!) { - if (platform == null) - { - throw new ArgumentNullException(nameof(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 6cc12c448c767c..462ca510be8fa5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Progress.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Progress.cs @@ -45,9 +45,9 @@ 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() { - _handler = handler ?? throw new ArgumentNullException(nameof(handler)); + _handler = handler; } /// Raised for each reported progress value. 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 3612e751aee285..c459b20f7f6cf4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs @@ -233,11 +233,8 @@ 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) { - if (rawAssembly == null) - throw new ArgumentNullException(nameof(rawAssembly)); - if (rawAssembly.Length == 0) throw new BadImageFormatException(SR.BadImageFormat_BadILFormat); @@ -249,11 +246,8 @@ 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!!) { - if (path == null) - throw new ArgumentNullException(nameof(path)); - if (PathInternal.IsPartiallyQualified(path)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, path), nameof(path)); @@ -335,11 +329,8 @@ 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!!) { - if (assemblyFile == null) - throw new ArgumentNullException(nameof(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 aa3864d1a415dd..32265d443bcda9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyFileVersionAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyFileVersionAttribute.cs @@ -6,9 +6,9 @@ namespace System.Reflection [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyFileVersionAttribute : Attribute { - public AssemblyFileVersionAttribute(string version) + public AssemblyFileVersionAttribute(string version!!) { - Version = version ?? throw new ArgumentNullException(nameof(version)); + Version = version; } public string Version { get; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs index b266f9e5c4d078..084805b66ce482 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs @@ -28,10 +28,8 @@ public sealed partial class AssemblyName : ICloneable, IDeserializationCallback, public AssemblyName(string assemblyName) : this() { - if (assemblyName == null) - throw new ArgumentNullException(nameof(assemblyName)); - if ((assemblyName.Length == 0) || - (assemblyName[0] == '\0')) + ArgumentException.ThrowIfNullOrEmpty(assemblyName); + if (assemblyName[0] == '\0') throw new ArgumentException(SR.Format_StringZeroLength); AssemblyNameParser.AssemblyNameParts parts = AssemblyNameParser.Parse(assemblyName); @@ -297,12 +295,8 @@ public static bool ReferenceMatchesDefinition(AssemblyName? reference, AssemblyN { if (object.ReferenceEquals(reference, definition)) return true; - - if (reference == null) - throw new ArgumentNullException(nameof(reference)); - - if (definition == null) - throw new ArgumentNullException(nameof(definition)); + ArgumentNullException.ThrowIfNull(reference); + ArgumentNullException.ThrowIfNull(definition); string refName = reference.Name ?? string.Empty; string defName = definition.Name ?? string.Empty; 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 69c9db7aba2c81..39d9968e0d84dc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeData.cs @@ -10,35 +10,23 @@ namespace System.Reflection public class CustomAttributeData { #region Public Static Members - public static IList GetCustomAttributes(MemberInfo target) + public static IList GetCustomAttributes(MemberInfo target!!) { - if (target is null) - throw new ArgumentNullException(nameof(target)); - return target.GetCustomAttributesData(); } - public static IList GetCustomAttributes(Module target) + public static IList GetCustomAttributes(Module target!!) { - if (target is null) - throw new ArgumentNullException(nameof(target)); - return target.GetCustomAttributesData(); } - public static IList GetCustomAttributes(Assembly target) + public static IList GetCustomAttributes(Assembly target!!) { - if (target is null) - throw new ArgumentNullException(nameof(target)); - return target.GetCustomAttributesData(); } - public static IList GetCustomAttributes(ParameterInfo target) + public static IList GetCustomAttributes(ParameterInfo target!!) { - if (target is null) - throw new ArgumentNullException(nameof(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 b2baa777460a6b..1ec818145a76af 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeNamedArgument.cs @@ -13,11 +13,8 @@ namespace System.Reflection private readonly MemberInfo _memberInfo; private readonly CustomAttributeTypedArgument _value; - public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value) + public CustomAttributeNamedArgument(MemberInfo memberInfo!!, object? value) { - if (memberInfo is null) - throw new ArgumentNullException(nameof(memberInfo)); - Type type = memberInfo switch { FieldInfo field => field.FieldType, @@ -29,9 +26,9 @@ public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value) _value = new CustomAttributeTypedArgument(type, value); } - public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) + public CustomAttributeNamedArgument(MemberInfo memberInfo!!, CustomAttributeTypedArgument typedArgument) { - _memberInfo = memberInfo ?? throw new ArgumentNullException(nameof(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 b0e306af8f838e..0ed140d4f821ea 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/CustomAttributeTypedArgument.cs @@ -15,20 +15,14 @@ namespace System.Reflection private readonly object? _value; private readonly Type _argumentType; - public CustomAttributeTypedArgument(Type argumentType, object? value) + public CustomAttributeTypedArgument(Type argumentType!!, object? value) { - if (argumentType is null) - throw new ArgumentNullException(nameof(argumentType)); - _value = CanonicalizeValue(value); _argumentType = argumentType; } - public CustomAttributeTypedArgument(object value) + public CustomAttributeTypedArgument(object value!!) { - if (value is null) - throw new ArgumentNullException(nameof(value)); - _value = CanonicalizeValue(value); _argumentType = value.GetType(); } 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 fc762fee949775..cbf100581b0037 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs @@ -35,27 +35,19 @@ 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!!) { - if (name == null) - throw new ArgumentNullException(nameof(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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (types == null) - throw new ArgumentNullException(nameof(types)); for (int i = 0; i < types.Length; i++) { - if (types[i] == null) - throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(types[i], nameof(types)); } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } 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 1a87dc84ee96bd..28a1902466407a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs @@ -63,13 +63,8 @@ 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!!) { - if (parameterInfo is null) - { - throw new ArgumentNullException(nameof(parameterInfo)); - } - EnsureIsSupported(); IList attributes = parameterInfo.GetCustomAttributesData(); @@ -179,13 +174,8 @@ private void CheckNullabilityAttributes(NullabilityInfo nullability, IListThe parameter which nullability info gets populated /// If the propertyInfo parameter is null /// - public NullabilityInfo Create(PropertyInfo propertyInfo) + public NullabilityInfo Create(PropertyInfo propertyInfo!!) { - if (propertyInfo is null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - EnsureIsSupported(); MethodInfo? getter = propertyInfo.GetGetMethod(true); @@ -235,13 +225,8 @@ 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!!) { - if (eventInfo is null) - { - throw new ArgumentNullException(nameof(eventInfo)); - } - EnsureIsSupported(); return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType!, CreateParser(eventInfo.GetCustomAttributesData())); @@ -255,13 +240,8 @@ 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!!) { - if (fieldInfo is null) - { - throw new ArgumentNullException(nameof(fieldInfo)); - } - EnsureIsSupported(); IList attributes = fieldInfo.GetCustomAttributesData(); 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 7cb11c5abe6dc7..3b7cd22a8adedb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs @@ -11,11 +11,8 @@ protected ReflectionContext() { } public abstract TypeInfo MapType(TypeInfo type); - public virtual TypeInfo GetTypeForObject(object value) + public virtual TypeInfo GetTypeForObject(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - return MapType(value.GetType().GetTypeInfo()); } } 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 7a1ae78f24eabf..f0950b7e45307b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/RuntimeReflectionExtensions.cs @@ -12,116 +12,72 @@ public static partial class RuntimeReflectionExtensions public static IEnumerable GetRuntimeFields( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] - this Type type) + this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetFields(Everything); } public static IEnumerable GetRuntimeMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] - this Type type) + this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetMethods(Everything); } public static IEnumerable GetRuntimeProperties( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] - this Type type) + this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetProperties(Everything); } public static IEnumerable GetRuntimeEvents( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] - this Type type) + this Type type!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetEvents(Everything); } public static FieldInfo? GetRuntimeField( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] - this Type type, string name) + this Type type!!, string name) { - if (type == null) - { - throw new ArgumentNullException(nameof(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) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetMethod(name, parameters); } public static PropertyInfo? GetRuntimeProperty( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] - this Type type, string name) + this Type type!!, string name) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetProperty(name); } public static EventInfo? GetRuntimeEvent( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] - this Type type, string name) + this Type type!!, string name) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } return type.GetEvent(name); } - public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method) + public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method!!) { - if (method == null) - { - throw new ArgumentNullException(nameof(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) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } return typeInfo.GetInterfaceMap(interfaceType); } - public static MethodInfo GetMethodInfo(this Delegate del) + public static MethodInfo GetMethodInfo(this Delegate del!!) { - if (del == null) - { - throw new ArgumentNullException(nameof(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 854a08f6a184c4..f5728ac0151308 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs @@ -9,14 +9,8 @@ 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!!) { - if (genericTypeDefinition is null) - throw new ArgumentNullException(nameof(genericTypeDefinition)); - - if (typeArguments is null) - throw new ArgumentNullException(nameof(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 d9de5027ce0a20..4551aaf0ce67f6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs @@ -27,11 +27,8 @@ 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!!) { - if (delegatingType is null) - throw new ArgumentNullException(nameof(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 14f582f0371075..134dc0a721e3be 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/NeutralResourcesLanguageAttribute.cs @@ -6,19 +6,14 @@ namespace System.Resources [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class NeutralResourcesLanguageAttribute : Attribute { - public NeutralResourcesLanguageAttribute(string cultureName) + public NeutralResourcesLanguageAttribute(string cultureName!!) { - if (cultureName == null) - throw new ArgumentNullException(nameof(cultureName)); - CultureName = cultureName; Location = UltimateResourceFallbackLocation.MainAssembly; } - public NeutralResourcesLanguageAttribute(string cultureName, UltimateResourceFallbackLocation location) + public NeutralResourcesLanguageAttribute(string cultureName!!, UltimateResourceFallbackLocation location) { - if (cultureName == null) - throw new ArgumentNullException(nameof(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 e928bcd21ea599..2c7ca1dddebdbc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -168,15 +168,10 @@ 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) { - if (null == baseName) - throw new ArgumentNullException(nameof(baseName)); - if (null == resourceDir) - throw new ArgumentNullException(nameof(resourceDir)); - BaseNameField = baseName; _moduleDir = resourceDir; @@ -188,12 +183,8 @@ private ResourceManager(string baseName, string resourceDir, _resourceGroveler = new FileBasedResourceGroveler(mediator); } - public ResourceManager(string baseName, Assembly assembly) + public ResourceManager(string baseName!!, Assembly assembly!!) { - if (null == baseName) - throw new ArgumentNullException(nameof(baseName)); - if (null == assembly) - throw new ArgumentNullException(nameof(assembly)); if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -203,14 +194,10 @@ 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) { - if (null == baseName) - throw new ArgumentNullException(nameof(baseName)); - if (null == assembly) - throw new ArgumentNullException(nameof(assembly)); if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -224,10 +211,8 @@ public ResourceManager(string baseName, Assembly assembly, CommonAssemblyInit(); } - public ResourceManager(Type resourceSource) + public ResourceManager(Type resourceSource!!) { - if (null == resourceSource) - throw new ArgumentNullException(nameof(resourceSource)); if (resourceSource is not RuntimeType) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -392,11 +377,8 @@ 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) { - if (null == culture) - throw new ArgumentNullException(nameof(culture)); - Dictionary? localResourceSets = _resourceSets; ResourceSet? rs; if (localResourceSets != null) @@ -527,14 +509,8 @@ private static void AddResourceSet(Dictionary localResource } } - protected static Version? GetSatelliteContractVersion(Assembly a) + protected static Version? GetSatelliteContractVersion(Assembly a!!) { - // Ensure that the assembly reference is not null - if (a == null) - { - throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly); - } - string? v = a.GetCustomAttribute()?.Version; if (v == null) { @@ -599,11 +575,8 @@ 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) { - if (null == name) - throw new ArgumentNullException(nameof(name)); - culture ??= CultureInfo.CurrentUICulture; ResourceSet? last = GetFirstResourceSet(culture); @@ -666,11 +639,8 @@ 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) { - if (null == name) - throw new ArgumentNullException(nameof(name)); - if (null == culture) { culture = CultureInfo.CurrentUICulture; @@ -747,12 +717,8 @@ internal sealed class ResourceManagerMediator { private readonly ResourceManager _rm; - internal ResourceManagerMediator(ResourceManager rm) + internal ResourceManagerMediator(ResourceManager rm!!) { - if (rm == null) - { - throw new ArgumentNullException(nameof(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 2153d23ee97c66..d87c3d1d122b33 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 @@ -126,10 +126,8 @@ 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) { - if (resourceName == null) - throw new ArgumentNullException(nameof(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 9aa2c73bb74719..31fb6574b06445 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,11 @@ public sealed partial class public #if RESOURCES_EXTENSIONS - DeserializingResourceReader(Stream stream) + DeserializingResourceReader(Stream stream!!) #else - ResourceReader(Stream stream) + ResourceReader(Stream stream!!) #endif { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); if (!stream.CanRead) throw new ArgumentException(SR.Argument_StreamNotReadable); 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 4cc4f920f8aed2..020d270b9fbb08 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceSet.cs @@ -58,10 +58,10 @@ public ResourceSet(Stream stream) ReadResources(); } - public ResourceSet(IResourceReader reader) + public ResourceSet(IResourceReader reader!!) : this() { - Reader = reader ?? throw new ArgumentNullException(nameof(reader)); + Reader = reader; ReadResources(); } @@ -198,11 +198,8 @@ protected virtual void ReadResources() // to help with some WinRes lifetime issues. } - private object? GetObjectInternal(string name) + private object? GetObjectInternal(string name!!) { - if (name == null) - throw new ArgumentNullException(nameof(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 90c55d9f304067..dd9e6e10e91600 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/RuntimeResourceSet.cs @@ -188,14 +188,11 @@ 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 == 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); @@ -263,11 +260,8 @@ 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 == 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 2691b72467f68e..d1b073405abaf7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/SatelliteContractVersionAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/SatelliteContractVersionAttribute.cs @@ -18,10 +18,8 @@ namespace System.Resources [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class SatelliteContractVersionAttribute : Attribute { - public SatelliteContractVersionAttribute(string version) + public SatelliteContractVersionAttribute(string version!!) { - if (version == null) - throw new ArgumentNullException(nameof(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 88b8187f3dfd22..2dc7c898b9ecb6 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 @@ -178,15 +178,9 @@ 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!!) { // key is validated by TryGetValue - - if (createValueCallback is null) - { - throw new ArgumentNullException(nameof(createValueCallback)); - } - return TryGetValue(key, out TValue? existingValue) ? existingValue : GetValueLocked(key, createValueCallback); 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 aed8034bc55f72..7083359bb0ed77 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 @@ -21,20 +21,8 @@ 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(string format, params object?[] arguments) - { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - - if (arguments == null) - { - throw new ArgumentNullException(nameof(arguments)); - } - - return new ConcreteFormattableString(format, arguments); - } + public static FormattableString Create(string format!!, params object?[] arguments!!) => + 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 498055ad6a1c51..68e96db5cc268e 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 @@ -66,13 +66,8 @@ 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) { - if (code == null) - throw new ArgumentNullException(nameof(code)); - if (backoutCode == null) - throw new ArgumentNullException(nameof(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 913cf3ae13abf5..7f091be304f082 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,10 +198,8 @@ 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) { - if (continuation == null) throw new ArgumentNullException(nameof(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 2ca88637df2f6c..a190b75504fef7 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,13 +36,8 @@ public sealed class TupleElementNamesAttribute : Attribute /// transformNames value of { "name1", "name2", null, null, /// null }. /// - public TupleElementNamesAttribute(string?[] transformNames) + public TupleElementNamesAttribute(string?[] transformNames!!) { - if (transformNames == null) - { - throw new ArgumentNullException(nameof(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 3e17c5b74d973c..03b0be93b195d3 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,15 +69,13 @@ 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) { - // Validate arguments - if (continuation == null) throw new ArgumentNullException(nameof(continuation)); - if (TplEventSource.Log.IsEnabled()) { continuation = OutputCorrelationEtwEvent(continuation); } + // Get the current SynchronizationContext, and if there is one, // post the continuation to it. However, treat the base type // as if there wasn't a SynchronizationContext, since that's what it 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 1279da2d974fa7..cc0888dc96b456 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,15 +27,8 @@ 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) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - return new ExceptionDispatchInfo(source); - } + public static ExceptionDispatchInfo Capture(Exception source!!) => + new ExceptionDispatchInfo(source); // Return the exception object represented by this ExceptionDispatchInfo instance public Exception SourceException => _exception; @@ -68,13 +61,8 @@ 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - source.SetCurrentStackTrace(); return source; @@ -98,17 +86,8 @@ 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (stackTrace is null) - { - throw new ArgumentNullException(nameof(stackTrace)); - } - source.SetRemoteStackTrace(stackTrace); return source; 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 b7f4c11f7ccb42..fe9d6f8c59688f 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,11 +218,8 @@ 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) { - if (progID == null) - throw new ArgumentNullException(nameof(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 b2e9302a8dd78f..d3e11be7f71030 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 @@ -105,33 +105,19 @@ public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen) } [RequiresDynamicCode("Marshalling code for the object might not be available. Use the SizeOf overload instead.")] - public static int SizeOf(object structure) + public static int SizeOf(object structure!!) { - if (structure is null) - { - throw new ArgumentNullException(nameof(structure)); - } - return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } - public static int SizeOf(T structure) + public static int SizeOf(T structure!!) { - if (structure is null) - { - throw new ArgumentNullException(nameof(structure)); - } - return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } [RequiresDynamicCode("Marshalling code for the object might not be available. Use the SizeOf overload instead.")] - public static int SizeOf(Type t) + public static int SizeOf(Type t!!) { - if (t is null) - { - throw new ArgumentNullException(nameof(t)); - } if (t is not RuntimeType) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); @@ -188,20 +174,14 @@ public static unsafe int Release(IntPtr pUnk) /// It must be used with EXTREME CAUTION since passing in invalid index or /// an array that is not pinned can cause unexpected results. /// - public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) + public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr!!, int index) { - if (arr is null) - throw new ArgumentNullException(nameof(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) { - if (arr is null) - throw new ArgumentNullException(nameof(arr)); - void* pRawData = Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(arr)); return (IntPtr)((byte*)pRawData + (uint)index * (nuint)Unsafe.SizeOf()); } @@ -248,15 +228,11 @@ 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) { - if (source is null) - throw new ArgumentNullException(nameof(source)); - if (destination == IntPtr.Zero) - throw new ArgumentNullException(nameof(destination)); + ArgumentNullException.ThrowIfNull(destination); // The rest of the argument validation is done by CopyTo - new Span(source, startIndex, length).CopyTo(new Span((void*)destination, length)); } @@ -300,12 +276,9 @@ 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) { - if (source == IntPtr.Zero) - throw new ArgumentNullException(nameof(source)); - if (destination is null) - throw new ArgumentNullException(nameof(destination)); + ArgumentNullException.ThrowIfNull(source); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); if (length < 0) @@ -541,25 +514,15 @@ 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!!) { - if (m is null) - { - throw new ArgumentNullException(nameof(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!!) { - if (c is null) - { - throw new ArgumentNullException(nameof(c)); - } - MethodInfo[] mi = c.GetMethods(); for (int i = 0; i < mi.Length; i++) @@ -582,17 +545,13 @@ public static void StructureToPtr([DisallowNull] T structure, IntPtr ptr, boo [RequiresDynamicCode("Marshalling code for the object might not be available")] public static object? PtrToStructure(IntPtr ptr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] - Type structureType) + Type structureType!!) { if (ptr == IntPtr.Zero) { return null; } - if (structureType is null) - { - throw new ArgumentNullException(nameof(structureType)); - } if (structureType.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType)); @@ -1118,12 +1077,8 @@ 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!!) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } if (type is not RuntimeType) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type)); @@ -1137,12 +1092,8 @@ public static Guid GenerateGuidForType(Type type) /// a PROGID in the metadata then it is returned otherwise a stable PROGID /// is generated based on the fully qualified name of the type. /// - public static string? GenerateProgIdForType(Type type) + public static string? GenerateProgIdForType(Type type!!) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } if (type.IsImport) { throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type)); @@ -1163,16 +1114,9 @@ public static Guid GenerateGuidForType(Type type) } [RequiresDynamicCode("Marshalling code for the delegate might not be available. Use the GetDelegateForFunctionPointer overload instead.")] - public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) + public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t!!) { - if (ptr == IntPtr.Zero) - { - throw new ArgumentNullException(nameof(ptr)); - } - if (t is null) - { - throw new ArgumentNullException(nameof(t)); - } + ArgumentNullException.ThrowIfNull(ptr); if (t is not RuntimeType) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t)); @@ -1218,13 +1162,8 @@ public static TDelegate GetDelegateForFunctionPointer(IntPtr ptr) } [RequiresDynamicCode("Marshalling code for the delegate might not be available. Use the GetFunctionPointerForDelegate overload instead.")] - public static IntPtr GetFunctionPointerForDelegate(Delegate d) + public static IntPtr GetFunctionPointerForDelegate(Delegate d!!) { - if (d is null) - { - throw new ArgumentNullException(nameof(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 681ad442f94ae4..0cd98bb914629d 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 @@ -36,11 +36,8 @@ 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!!) { - if (libraryPath == null) - throw new ArgumentNullException(nameof(libraryPath)); - return LoadFromPath(libraryPath, throwOnError: true); } @@ -51,11 +48,8 @@ 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) { - if (libraryPath == null) - throw new ArgumentNullException(nameof(libraryPath)); - handle = LoadFromPath(libraryPath, throwOnError: false); return handle != IntPtr.Zero; } @@ -82,12 +76,8 @@ 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) { - if (libraryName == null) - throw new ArgumentNullException(nameof(libraryName)); - if (assembly == null) - throw new ArgumentNullException(nameof(assembly)); if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -118,12 +108,8 @@ public static IntPtr Load(string libraryName, Assembly assembly, DllImportSearch /// 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) { - if (libraryName == null) - throw new ArgumentNullException(nameof(libraryName)); - if (assembly == null) - throw new ArgumentNullException(nameof(assembly)); if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); @@ -156,12 +142,9 @@ 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!!) { - if (handle == IntPtr.Zero) - throw new ArgumentNullException(nameof(handle)); - if (name == null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(handle); return GetSymbol(handle, name, throwOnError: true); } @@ -174,13 +157,9 @@ 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) { - if (handle == IntPtr.Zero) - throw new ArgumentNullException(nameof(handle)); - if (name == null) - throw new ArgumentNullException(nameof(name)); - + ArgumentNullException.ThrowIfNull(handle); address = GetSymbol(handle, name, throwOnError: false); return address != IntPtr.Zero; } @@ -205,12 +184,8 @@ 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!!) { - if (assembly == null) - throw new ArgumentNullException(nameof(assembly)); - if (resolver == null) - throw new ArgumentNullException(nameof(resolver)); if (assembly is not RuntimeAssembly) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); 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 c6c0c29dea8b4c..178d81b5cc7e31 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,15 +34,8 @@ public sealed partial class PosixSignalRegistration : IDisposable [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] - public static PosixSignalRegistration Create(PosixSignal signal, Action handler) - { - if (handler is null) - { - throw new ArgumentNullException(nameof(handler)); - } - - return Register(signal, handler); - } + public static PosixSignalRegistration Create(PosixSignal signal, Action handler!!) => + 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 7fe55f25b34d66..bad9b6d9d0b8c4 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 @@ -213,11 +213,9 @@ 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 { - if (array == null) - throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) @@ -302,11 +300,9 @@ 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 { - if (array == null) - throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); 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 68ed52102dc1c1..1ed1959ebd1261 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,13 +31,8 @@ public sealed class AssemblyDependencyResolver private readonly string[] _resourceSearchPaths; private readonly string[] _assemblyDirectorySearchPaths; - public AssemblyDependencyResolver(string componentAssemblyPath) + public AssemblyDependencyResolver(string componentAssemblyPath!!) { - if (componentAssemblyPath == null) - { - throw new ArgumentNullException(nameof(componentAssemblyPath)); - } - string? assemblyPathsList = null; string? nativeSearchPathsList = null; string? resourceSearchPathsList = null; @@ -110,13 +105,8 @@ public AssemblyDependencyResolver(string componentAssemblyPath) _assemblyDirectorySearchPaths = new string[1] { Path.GetDirectoryName(componentAssemblyPath)! }; } - public string? ResolveAssemblyToPath(AssemblyName assemblyName) + public string? ResolveAssemblyToPath(AssemblyName assemblyName!!) { - if (assemblyName == null) - { - throw new ArgumentNullException(nameof(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' @@ -161,13 +151,8 @@ public AssemblyDependencyResolver(string componentAssemblyPath) return null; } - public string? ResolveUnmanagedDllToPath(string unmanagedDllName) + public string? ResolveUnmanagedDllToPath(string unmanagedDllName!!) { - if (unmanagedDllName == null) - { - throw new ArgumentNullException(nameof(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 c6b3478cf9bb69..d67ae7a2e9aaff 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,13 +293,8 @@ 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!!) { - if (assemblyPath == null) - { - throw new ArgumentNullException(nameof(assemblyPath)); - } - return AssemblyName.GetAssemblyName(assemblyPath); } @@ -313,11 +308,8 @@ 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!!) { - if (assemblyName == null) - throw new ArgumentNullException(nameof(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); @@ -327,13 +319,8 @@ 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!!) { - if (assemblyPath == null) - { - throw new ArgumentNullException(nameof(assemblyPath)); - } - if (PathInternal.IsPartiallyQualified(assemblyPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath)); @@ -348,13 +335,8 @@ 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) { - if (nativeImagePath == null) - { - throw new ArgumentNullException(nameof(nativeImagePath)); - } - if (PathInternal.IsPartiallyQualified(nativeImagePath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, nativeImagePath), nameof(nativeImagePath)); @@ -380,13 +362,8 @@ 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) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(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 863e04326086e0..a3bc75a04aae65 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,18 +24,8 @@ public sealed partial class SerializationInfo private Type _rootType; [CLSCompliant(false)] - public SerializationInfo(Type type, IFormatterConverter converter) + public SerializationInfo(Type type!!, IFormatterConverter converter!!) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (converter == null) - { - throw new ArgumentNullException(nameof(converter)); - } - _rootType = type; _rootTypeName = type.FullName!; _rootTypeAssemblyName = type.Module.Assembly.FullName!; @@ -89,13 +79,8 @@ public string AssemblyName public bool IsAssemblyNameSetExplicit { get; private set; } - public void SetType(Type type) + public void SetType(Type type!!) { - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - if (!ReferenceEquals(_rootType, type)) { _rootType = type; @@ -143,18 +128,8 @@ private void ExpandArrays() _types = newTypes; } - public void AddValue(string name, object? value, Type type) + public void AddValue(string name!!, object? value, Type type!!) { - if (name is null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (type is null) - { - throw new ArgumentNullException(nameof(type)); - } - AddValueInternal(name, value, type); } @@ -300,12 +275,8 @@ public void UpdateValue(string name, object value, Type type) } } - private int FindElement(string name) + private int FindElement(string name!!) { - if (null == name) - { - throw new ArgumentNullException(nameof(name)); - } if (_nameToIndex.TryGetValue(name, out int index)) { return index; @@ -354,13 +325,8 @@ private int FindElement(string name) return _values[index]; } - public object? GetValue(string name, Type type) + public object? GetValue(string name, Type type!!) { - if (type is null) - { - throw new ArgumentNullException(nameof(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 035e6b41bf4a47..adaf7f107db40b 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,10 +20,8 @@ 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!!) { - if (frameworkName == null) - throw new ArgumentNullException(nameof(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 8ad94b514bfa1c..0538f4efab7789 100644 --- a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs @@ -53,11 +53,8 @@ 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) { - if (attributeType is null) - throw new ArgumentNullException(nameof(attributeType)); - if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -94,11 +91,8 @@ public override MemberInfo[] GetDefaultMembers() public override Type GetElementType() => RuntimeTypeHandle.GetElementType(this); - public override string? GetEnumName(object value) + public override string? GetEnumName(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - Type valueType = value.GetType(); if (!(valueType.IsEnum || IsIntegerType(valueType))) @@ -238,22 +232,16 @@ 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) { - if (attributeType is null) - throw new ArgumentNullException(nameof(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!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); @@ -369,7 +357,7 @@ 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) { const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF; @@ -479,10 +467,6 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) // PutDispProperty and\or PutRefDispProperty ==> SetProperty. if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0) bindingFlags |= BindingFlags.SetProperty; - - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (name.Length == 0 || name.Equals("[DISPID=0]")) { // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString @@ -789,16 +773,11 @@ 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) { - if (genericArguments == null) - throw new ArgumentNullException(); - for (int i = 0; i < genericArguments.Length; i++) { - if (genericArguments[i] == null) - throw new ArgumentNullException(); - + ArgumentNullException.ThrowIfNull(genericArguments[i], null); ThrowIfTypeNeverValidGenericArgument(genericArguments[i]); } 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 21c6591dc711f5..1eada13c2c8d98 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecureString.cs @@ -22,12 +22,8 @@ public SecureString() } [CLSCompliant(false)] - public unsafe SecureString(char* value, int length) + public unsafe SecureString(char* value!!, int length) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 f48c702651fecc..9b6ed8d5e7694b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs @@ -31,22 +31,16 @@ public sealed class SecurityElement //-------------------------- Constructors --------------------------- - public SecurityElement(string tag) + public SecurityElement(string tag!!) { - if (tag == null) - throw new ArgumentNullException(nameof(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) { - if (tag == null) - throw new ArgumentNullException(nameof(tag)); - if (!IsValidTag(tag)) throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag)); @@ -191,14 +185,8 @@ internal void AddAttributeSafe(string name, string value) _attributes.Add(value); } - public void AddAttribute(string name, string value) + public void AddAttribute(string name!!, string value!!) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (!IsValidAttributeName(name)) throw new ArgumentException(SR.Format(SR.Argument_InvalidElementName, name)); @@ -208,11 +196,8 @@ public void AddAttribute(string name, string value) AddAttributeSafe(name, value); } - public void AddChild(SecurityElement child) + public void AddChild(SecurityElement child!!) { - if (child == null) - throw new ArgumentNullException(nameof(child)); - _children ??= new ArrayList(ChildrenTypical); _children.Add(child); @@ -497,11 +482,8 @@ private void ToString(object obj, Action write) } } - public string? Attribute(string name) + public string? Attribute(string name!!) { - if (name == null) - throw new ArgumentNullException(nameof(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) @@ -529,12 +511,10 @@ private void ToString(object obj, Action write) return null; } - public SecurityElement? SearchForChildByTag(string tag) + public SecurityElement? SearchForChildByTag(string tag!!) { // Go through all the children and see if we can // find the ones that are asked for (matching tags) - if (tag == null) - throw new ArgumentNullException(nameof(tag)); // Note: we don't check for a valid tag here because // an invalid tag simply won't be found. @@ -548,12 +528,10 @@ private void ToString(object obj, Action write) return null; } - public string? SearchForTextOfTag(string tag) + public string? SearchForTextOfTag(string tag!!) { // Search on each child in order and each // child's child, depth-first - if (tag == null) - throw new ArgumentNullException(nameof(tag)); // Note: we don't check for a valid tag here because // an invalid tag simply won't be found. @@ -571,12 +549,6 @@ private void ToString(object obj, Action write) return null; } - public static SecurityElement? FromString(string xml) - { - if (xml == null) - throw new ArgumentNullException(nameof(xml)); - - return default; - } + public static SecurityElement? FromString(string xml!!) => default; } } 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 6a059351f376ac..8860c7a660ba12 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs @@ -541,13 +541,8 @@ public bool EndsWith(string value) return EndsWith(value, StringComparison.CurrentCulture); } - public bool EndsWith(string value, StringComparison comparisonType) + public bool EndsWith(string value!!, StringComparison comparisonType) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - if ((object)this == (object)value) { CheckStringComparison(comparisonType); @@ -584,13 +579,8 @@ 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) { - if (null == value) - { - throw new ArgumentNullException(nameof(value)); - } - if ((object)this == (object)value) { return true; @@ -947,22 +937,13 @@ 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!!) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } return StartsWith(value, StringComparison.CurrentCulture); } - public bool StartsWith(string value, StringComparison comparisonType) + public bool StartsWith(string value!!, StringComparison comparisonType) { - if (value is null) - { - throw new ArgumentNullException(nameof(value)); - } - if ((object)this == (object)value) { CheckStringComparison(comparisonType); @@ -1009,13 +990,8 @@ ref Unsafe.As(ref value.GetRawStringData()), } } - public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture) + public bool StartsWith(string value!!, bool ignoreCase, CultureInfo? culture) { - if (null == value) - { - throw new ArgumentNullException(nameof(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 0097b92631ff0e..e7e9075791a90f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -41,13 +41,8 @@ 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!!) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } - if (args.Length <= 1) { return args.Length == 0 ? @@ -106,11 +101,8 @@ public static string Concat(params object?[] args) return result; } - public static string Concat(IEnumerable values) + public static string Concat(IEnumerable values!!) { - if (values == null) - throw new ArgumentNullException(nameof(values)); - if (typeof(T) == typeof(char)) { // Special-case T==char, as we can handle that case much more efficiently, @@ -190,11 +182,8 @@ public static string Concat(IEnumerable values) } } - public static string Concat(IEnumerable values) + public static string Concat(IEnumerable values!!) { - if (values == null) - throw new ArgumentNullException(nameof(values)); - using (IEnumerator en = values.GetEnumerator()) { if (!en.MoveNext()) @@ -371,11 +360,8 @@ 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!!) { - if (values == null) - throw new ArgumentNullException(nameof(values)); - if (values.Length <= 1) { return values.Length == 0 ? @@ -493,21 +479,16 @@ public static string Format(IFormatProvider? provider, string format, params obj 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) { - if (format == null) - throw new ArgumentNullException(nameof(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!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); if ((uint)startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex)); @@ -556,12 +537,8 @@ 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) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -1202,13 +1179,8 @@ 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!!) { - if (replacementText is null) - { - throw new ArgumentNullException(nameof(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 260c87b5fd9118..fe5c9d14baaeeb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.cs @@ -81,11 +81,8 @@ 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) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -308,11 +305,8 @@ 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!!) { - if (action == null) - throw new ArgumentNullException(nameof(action)); - if (length <= 0) { if (length == 0) @@ -371,11 +365,8 @@ public object Clone() return this; } - public static unsafe string Copy(string str) + public static unsafe string Copy(string str!!) { - if (str == null) - throw new ArgumentNullException(nameof(str)); - string result = FastAllocateString(str.Length); Buffer.Memmove( @@ -391,10 +382,8 @@ 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) { - if (destination == null) - throw new ArgumentNullException(nameof(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 ce22da699c9284..d013b563b6f61a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/StringComparer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/StringComparer.cs @@ -42,23 +42,13 @@ public static StringComparer FromComparison(StringComparison comparisonType) }; } - public static StringComparer Create(CultureInfo culture, bool ignoreCase) + public static StringComparer Create(CultureInfo culture!!, bool ignoreCase) { - if (culture == null) - { - throw new ArgumentNullException(nameof(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) { - if (culture == null) - { - throw new ArgumentNullException(nameof(culture)); - } - return new CultureAwareComparer(culture, options); } @@ -195,13 +185,8 @@ public int Compare(object? x, object? y) return x.Equals(y); } - public int GetHashCode(object obj) + public int GetHashCode(object obj!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - if (obj is string s) { return GetHashCode(s); @@ -269,12 +254,8 @@ 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!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(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 f858bb7d2b72a0..63371135495128 100644 --- a/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/StringNormalizationExtensions.cs @@ -12,13 +12,8 @@ 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) { - if (strInput == null) - { - throw new ArgumentNullException(nameof(strInput)); - } - return strInput.IsNormalized(normalizationForm); } @@ -28,13 +23,8 @@ 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) { - if (strInput == null) - { - throw new ArgumentNullException(nameof(strInput)); - } - return strInput.Normalize(normalizationForm); } } 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 34270ba3c30ade..d19f9c008572a6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/DecoderReplacementFallback.cs @@ -18,11 +18,8 @@ public DecoderReplacementFallback() : this("?") { } - public DecoderReplacementFallback(string replacement) + public DecoderReplacementFallback(string replacement!!) { - if (replacement == null) - throw new ArgumentNullException(nameof(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/EncoderReplacementFallback.cs b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs index 709695ce36dd11..376e865d7b15f0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncoderReplacementFallback.cs @@ -18,12 +18,8 @@ public EncoderReplacementFallback() : this("?") { } - public EncoderReplacementFallback(string replacement) + public EncoderReplacementFallback(string replacement!!) { - // Must not be null - if (replacement == null) - throw new ArgumentNullException(nameof(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 b236e125e73aaa..731a8c92cceeab 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Encoding.cs @@ -175,12 +175,8 @@ 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!!) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes)); - return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length); } @@ -189,20 +185,9 @@ public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, // 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) { - if (srcEncoding == null || dstEncoding == null) - { - throw new ArgumentNullException(srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding), - SR.ArgumentNull_Array); - } - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes), - SR.ArgumentNull_Array); - } - return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); } @@ -491,8 +476,7 @@ public EncoderFallback EncoderFallback if (this.IsReadOnly) throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); - if (value == null) - throw new ArgumentNullException(nameof(value)); + ArgumentNullException.ThrowIfNull(value); encoderFallback = value; } @@ -506,8 +490,7 @@ public DecoderFallback DecoderFallback if (this.IsReadOnly) throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); - if (value == null) - throw new ArgumentNullException(nameof(value)); + ArgumentNullException.ThrowIfNull(value); decoderFallback = value; } @@ -539,14 +522,8 @@ 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!!) { - if (chars == null) - { - throw new ArgumentNullException(nameof(chars), - SR.ArgumentNull_Array); - } - return GetByteCount(chars, 0, chars.Length); } @@ -568,11 +545,8 @@ 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) { - if (s == null) - throw new ArgumentNullException(nameof(s), - SR.ArgumentNull_String); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -597,13 +571,9 @@ 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 - if (chars == null) - throw new ArgumentNullException(nameof(chars), - SR.ArgumentNull_Array); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -624,13 +594,8 @@ 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!!) { - if (chars == null) - { - throw new ArgumentNullException(nameof(chars), - SR.ArgumentNull_Array); - } return GetBytes(chars, 0, chars.Length); } @@ -659,12 +624,8 @@ 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!!) { - if (s == null) - throw new ArgumentNullException(nameof(s), - SR.ArgumentNull_String); - int byteCount = GetByteCount(s); byte[] bytes = new byte[byteCount]; int bytesReceived = GetBytes(s, 0, s.Length, bytes, 0); @@ -675,11 +636,8 @@ 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) { - if (s == null) - throw new ArgumentNullException(nameof(s), - SR.ArgumentNull_String); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -738,14 +696,10 @@ 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 - if (bytes == null || chars == null) - throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), - SR.ArgumentNull_Array); - if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -787,13 +741,8 @@ 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!!) { - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes), - SR.ArgumentNull_Array); - } return GetCharCount(bytes, 0, bytes.Length); } @@ -805,13 +754,9 @@ 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 - if (bytes == null) - throw new ArgumentNullException(nameof(bytes), - SR.ArgumentNull_Array); - if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -832,13 +777,8 @@ 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!!) { - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes), - SR.ArgumentNull_Array); - } return GetChars(bytes, 0, bytes.Length); } @@ -883,14 +823,10 @@ 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 - if (chars == null || bytes == null) - throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), - SR.ArgumentNull_Array); - if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -930,11 +866,8 @@ 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) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); - if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -1026,12 +959,8 @@ 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!!) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes), - SR.ArgumentNull_Array); - return GetString(bytes, 0, bytes.Length); } @@ -1109,23 +1038,8 @@ 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) { - if (innerStream is null) - { - throw new ArgumentNullException(nameof(innerStream)); - } - - if (innerStreamEncoding is null) - { - throw new ArgumentNullException(nameof(innerStreamEncoding)); - } - - if (outerStreamEncoding is null) - { - throw new ArgumentNullException(nameof(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 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 55a0bd3de6af9b..6eeddcb74af5aa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingInfo.cs @@ -15,13 +15,8 @@ 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) { - if (name == null || displayName == null || provider == null) - { - throw new ArgumentNullException(name == null ? nameof(name) : (displayName == null ? nameof(displayName) : nameof(provider))); - } - 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 3e8723c9fcab57..b380c2b01ca9c2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingProvider.cs @@ -43,13 +43,8 @@ public EncodingProvider() { } public virtual IEnumerable GetEncodings() => Array.Empty(); - internal static void AddProvider(EncodingProvider provider) + internal static void AddProvider(EncodingProvider provider!!) { - if (provider is null) - { - throw new ArgumentNullException(nameof(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 bdf608fc76b6e7..d548f5f405152c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/EncodingTable.cs @@ -28,11 +28,8 @@ 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!!) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - object? codePageObj = s_nameToCodePage[name]; if (codePageObj != null) 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 8a8d6a93b57948..189e6e2e105235 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -181,13 +181,8 @@ public StringBuilder(int capacity, int maxCapacity) m_ChunkChars = GC.AllocateUninitializedArray(capacity); } - private StringBuilder(SerializationInfo info, StreamingContext context) + private StringBuilder(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - int persistedCapacity = 0; string? persistedString = null; int persistedMaxCapacity = int.MaxValue; @@ -244,13 +239,8 @@ private StringBuilder(SerializationInfo info, StreamingContext context) AssertInvariants(); } - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - AssertInvariants(); info.AddValue(MaxCapacityField, m_MaxCapacity); info.AddValue(CapacityField, Capacity); @@ -909,13 +899,8 @@ 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) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } - if (destinationIndex < 0) { throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(destinationIndex))); @@ -1442,13 +1427,8 @@ 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) { - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - int pos = 0; int len = format.Length; char ch = '\x0'; 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 d11eae6ce47b9e..e7e2ab817e65f7 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 @@ -57,17 +57,12 @@ internal void AppendSpanFormattable(T value, string? format, IFormatProvider? // 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) { // 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 - if (format == null) - { - throw new ArgumentNullException(nameof(format)); - } - int pos = 0; int len = format.Length; char ch = '\0'; 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 27f29cb0dd9498..fa25723d55529d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationToken.cs @@ -281,11 +281,8 @@ 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) { - if (callback == null) - throw new ArgumentNullException(nameof(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 42b9dd61f5328f..3fa24dff5057f8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -754,14 +754,8 @@ 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) - { - if (tokens == null) - { - throw new ArgumentNullException(nameof(tokens)); - } - - return tokens.Length switch + public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens!!) => + tokens.Length switch { 0 => throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty), 1 => CreateLinkedTokenSource(tokens[0]), @@ -771,7 +765,6 @@ 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 be997e3c0965b7..35e10264ea5d34 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CompressedStack.cs @@ -31,13 +31,8 @@ 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) { - if (compressedStack == null) - { - throw new ArgumentNullException(nameof(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/SpinWait.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs index 66b73f8be02522..4ebd8547287518 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SpinWait.cs @@ -310,10 +310,7 @@ public static bool SpinUntil(Func condition, int millisecondsTimeout) throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong); } - if (condition == null) - { - throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull); - } + ArgumentNullException.ThrowIfNull(condition); uint startTime = 0; if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite) { 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 b3ed9d1b9691f9..984ba13db2d02e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs @@ -42,13 +42,8 @@ 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) { - if (waitHandles == null) - { - throw new ArgumentNullException(nameof(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 a8d80715ed3fee..380fc307a9fb65 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,10 +96,8 @@ 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) { - // Validate arguments - if (taskScheduler == null) throw new ArgumentNullException(nameof(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/Sources/ManualResetValueTaskSourceCore.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs index dc1fa4eb546488..12321fbec693db 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,12 +115,8 @@ 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) { - if (continuation == null) - { - throw new ArgumentNullException(nameof(continuation)); - } ValidateToken(token); if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0) 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 ca622b686d813d..05704234f6cb97 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,39 +9,23 @@ 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) - { - if (task == null) - { - throw new ArgumentNullException(nameof(task)); - } - + public static Task Unwrap(this Task 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. - return - !task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise(task, lookForOce: false) : - task.Result ?? - Task.FromCanceled(new CancellationToken(true)); - } + !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) - { - if (task == null) - { - throw new ArgumentNullException(nameof(task)); - } - + public static Task Unwrap(this Task> 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. - return - !task.IsCompletedSuccessfully ? Task.CreateUnwrapPromise(task, lookForOce: false) : - task.Result ?? - Task.FromCanceled(new CancellationToken(true)); - } + !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 9156d4fcdb9a82..cdbf52ed8099f3 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 @@ -1678,6 +1678,7 @@ internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) return promise; } + /// /// Creates a continuation Task /// that will be started upon the completion of a set of provided Tasks. @@ -1694,14 +1695,11 @@ 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!!) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } - /// /// Creates a continuation Task /// that will be started upon the completion of a set of provided Tasks. @@ -1723,10 +1721,8 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1757,10 +1753,8 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can /// 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1801,11 +1795,9 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Tas /// 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1826,10 +1818,8 @@ public Task ContinueWhenAll(Task[] tasks, Action continuationAction, Can /// 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!!) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1856,11 +1846,9 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -1892,11 +1880,9 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1938,11 +1924,9 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -1966,10 +1950,8 @@ 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!!) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -1999,10 +1981,8 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2037,10 +2017,8 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2085,11 +2063,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2115,10 +2091,8 @@ 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!!) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2148,11 +2122,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2188,11 +2160,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2238,11 +2208,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2414,10 +2382,8 @@ 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!!) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2442,10 +2408,8 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2476,10 +2440,8 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance /// 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2520,11 +2482,9 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, TaskC /// 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } @@ -2549,10 +2509,8 @@ public Task ContinueWhenAny(Task[] tasks, Action continuationAction, Cance /// 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!!) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2581,10 +2539,8 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2619,10 +2575,8 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2667,11 +2621,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2696,9 +2648,8 @@ 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!!) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2728,11 +2679,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2768,11 +2717,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2818,11 +2765,9 @@ 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) { - if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } @@ -2844,10 +2789,8 @@ 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!!) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2873,11 +2816,9 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } @@ -2909,11 +2850,9 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(continuationAction)); - return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } @@ -2955,20 +2894,16 @@ 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) { - if (continuationAction == null) throw new ArgumentNullException(nameof(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!!) { - if (tasks == null) - throw new ArgumentNullException(nameof(tasks)); if (tasks.Length == 0) throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks)); @@ -2984,10 +2919,8 @@ internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) return tasksCopy; } - internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) + internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks!!) { - if (tasks == null) - throw new ArgumentNullException(nameof(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 43c30ecbfcf810..ad062d66024d5a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -107,24 +107,15 @@ private void InitializeCulture() } } - public Thread(ThreadStart start) + public Thread(ThreadStart start!!) { - if (start == null) - { - throw new ArgumentNullException(nameof(start)); - } - _startHelper = new StartHelper(start); Initialize(); } - public Thread(ThreadStart start, int maxStackSize) + public Thread(ThreadStart start!!, int maxStackSize) { - if (start == null) - { - throw new ArgumentNullException(nameof(start)); - } if (maxStackSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -135,24 +126,15 @@ public Thread(ThreadStart start, int maxStackSize) Initialize(); } - public Thread(ParameterizedThreadStart start) + public Thread(ParameterizedThreadStart start!!) { - if (start == null) - { - throw new ArgumentNullException(nameof(start)); - } - _startHelper = new StartHelper(start); Initialize(); } - public Thread(ParameterizedThreadStart start, int maxStackSize) + public Thread(ParameterizedThreadStart start!!, int maxStackSize) { - if (start == null) - { - throw new ArgumentNullException(nameof(start)); - } if (maxStackSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -248,13 +230,8 @@ private void RequireCurrentThread() } } - private void SetCultureOnUnstartedThread(CultureInfo value, bool uiCulture) + private void SetCultureOnUnstartedThread(CultureInfo value!!, bool uiCulture) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - StartHelper? startHelper = _startHelper; // This check is best effort to catch common user errors only. It won't catch all posssible race @@ -625,13 +602,8 @@ public static void FreeNamedSlot(string name) } } - private static ThreadLocal GetThreadLocal(LocalDataStoreSlot slot) + private static ThreadLocal GetThreadLocal(LocalDataStoreSlot slot!!) { - if (slot == null) - { - throw new ArgumentNullException(nameof(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 cf05a40a68e6d4..ec6a28efbb5ecb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadLocal.cs @@ -89,11 +89,8 @@ public ThreadLocal(bool trackAllValues) /// /// is a null reference (Nothing in Visual Basic). /// - public ThreadLocal(Func valueFactory) + public ThreadLocal(Func valueFactory!!) { - if (valueFactory == null) - throw new ArgumentNullException(nameof(valueFactory)); - Initialize(valueFactory, false); } @@ -109,11 +106,8 @@ public ThreadLocal(Func valueFactory) /// /// is a null reference (Nothing in Visual Basic). /// - public ThreadLocal(Func valueFactory, bool trackAllValues) + public ThreadLocal(Func valueFactory!!, bool trackAllValues) { - if (valueFactory == null) - throw new ArgumentNullException(nameof(valueFactory)); - Initialize(valueFactory, trackAllValues); } 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 108034d778d423..af28c7e3aa9932 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -882,15 +882,12 @@ 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) { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - _timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, flowExecutionContext)); } @@ -949,11 +946,8 @@ public static long ActiveCount } } - public bool Dispose(WaitHandle notifyObject) + public bool Dispose(WaitHandle notifyObject!!) { - if (notifyObject == null) - throw new ArgumentNullException(nameof(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 f65555ae04e81a..ea799f79acb24b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -196,7 +196,7 @@ private static void ObtainSafeWaitHandles( WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) { - throw new ArgumentNullException("waitHandles[" + i + ']', SR.ArgumentNull_ArrayElement); + throw new ArgumentNullException($"waitHandles[{i}]", SR.ArgumentNull_ArrayElement); } SafeWaitHandle safeWaitHandle = waitHandle._waitHandle ?? @@ -238,13 +238,8 @@ private static void ObtainSafeWaitHandles( } } - private static int WaitMultiple(WaitHandle[] waitHandles, bool waitAll, int millisecondsTimeout) + private static int WaitMultiple(WaitHandle[] waitHandles!!, bool waitAll, int millisecondsTimeout) { - if (waitHandles == null) - { - throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles); - } - return WaitMultiple(new ReadOnlySpan(waitHandles), waitAll, millisecondsTimeout); } @@ -353,16 +348,8 @@ 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) { - if (toSignal == null) - { - throw new ArgumentNullException(nameof(toSignal)); - } - if (toWaitOn == null) - { - throw new ArgumentNullException(nameof(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 f68aa84db76394..9b6712c81109b3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandleExtensions.cs @@ -12,29 +12,15 @@ public static class WaitHandleExtensions /// /// The to operate on. /// A representing the native operating system handle. - public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle) - { - if (waitHandle == null) - { - throw new ArgumentNullException(nameof(waitHandle)); - } - - return waitHandle.SafeWaitHandle; - } + public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle!!) => + 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) - { - if (waitHandle == null) - { - throw new ArgumentNullException(nameof(waitHandle)); - } - + public static void SetSafeWaitHandle(this WaitHandle waitHandle!!, SafeWaitHandle? value) => 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 7c754b4f285708..6650d80948c704 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.AdjustmentRule.cs @@ -260,13 +260,8 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) @@ -276,13 +271,8 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex info.AddValue("NoDaylightTransitions", _noDaylightTransitions); // Do not rename (binary serialization) } - private AdjustmentRule(SerializationInfo info, StreamingContext context) + private AdjustmentRule(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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 199b1dad8971c0..53808118d47cab 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.TransitionTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.TransitionTime.cs @@ -127,13 +127,8 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) @@ -142,13 +137,8 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex info.AddValue("IsFixedDateRule", _isFixedDateRule); // Do not rename (binary serialization) } - private TransitionTime(SerializationInfo info, StreamingContext context) + private TransitionTime(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs index f0b865a3a48578..9f4905e511b12f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.cs @@ -289,11 +289,8 @@ public static TimeZoneInfo FindSystemTimeZoneById(string id) return Utc; } - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - else if (id.Length == 0 || id.Contains('\0')) + ArgumentNullException.ThrowIfNull(id); + if (id.Length == 0 || id.Contains('\0')) { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); } 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 7bdfce06f1b691..391f39e1693a8f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs @@ -320,7 +320,7 @@ 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!!) { // Special case for Utc to avoid having TryGetTimeZone creating a new Utc object if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase)) @@ -328,10 +328,6 @@ public static TimeZoneInfo FindSystemTimeZoneById(string id) return Utc; } - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0')) { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs index 095cce8ba35e8e..80a256c99cf56f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.cs @@ -582,13 +582,8 @@ 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!!) { - if (destinationTimeZone == null) - { - throw new ArgumentNullException(nameof(destinationTimeZone)); - } - // calculate the destination time zone offset DateTime utcDateTime = dateTimeOffset.UtcDateTime; TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone); @@ -605,13 +600,8 @@ 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!!) { - if (destinationTimeZone == null) - { - throw new ArgumentNullException(nameof(destinationTimeZone)); - } - // Special case to give a way clearing the cache without exposing ClearCachedData() if (dateTime.Ticks == 0) { @@ -634,18 +624,8 @@ 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) { - if (sourceTimeZone == null) - { - throw new ArgumentNullException(nameof(sourceTimeZone)); - } - - if (destinationTimeZone == null) - { - throw new ArgumentNullException(nameof(destinationTimeZone)); - } - DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone); if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind)) { @@ -757,12 +737,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } if (source.Length == 0) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source)); @@ -819,13 +795,8 @@ public static ReadOnlyCollection GetSystemTimeZones() /// /// Value equality on the "adjustmentRules" array /// - public bool HasSameRules(TimeZoneInfo other) + public bool HasSameRules(TimeZoneInfo other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - // check the utcOffset and supportsDaylightSavingTime members if (_baseUtcOffset != other._baseUtcOffset || _supportsDaylightSavingTime != other._supportsDaylightSavingTime) @@ -1019,13 +990,8 @@ void IDeserializationCallback.OnDeserialization(object? sender) } } - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) @@ -1035,13 +1001,8 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization) } - private TimeZoneInfo(SerializationInfo info, StreamingContext context) + private TimeZoneInfo(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) @@ -2023,15 +1984,7 @@ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool /// private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[]? adjustmentRules, out bool adjustmentRulesSupportDst) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - - if (id.Length == 0) - { - throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id)); - } + ArgumentException.ThrowIfNullOrEmpty(id); if (UtcOffsetOutOfRange(baseUtcOffset)) { 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 50bbf971cf5aee..e088eae799c6ae 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs @@ -17,11 +17,8 @@ namespace System // public abstract partial class Type { - public virtual bool IsEnumDefined(object value) + public virtual bool IsEnumDefined(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (!IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value)); @@ -64,11 +61,8 @@ public virtual bool IsEnumDefined(object value) } } - public virtual string? GetEnumName(object value) + public virtual string? GetEnumName(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - 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 d9ac8b0c788d00..71cb7b5e756065 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs @@ -115,11 +115,8 @@ public bool IsVisible } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] - public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) + public virtual Type[] FindInterfaces(TypeFilter filter!!, object? filterCriteria) { - if (filter == null) - throw new ArgumentNullException(nameof(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 bd3c449d74cd58..f34dfa92c59c9e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -157,10 +157,8 @@ 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) { - if (types == null) - throw new ArgumentNullException(nameof(types)); for (int i = 0; i < types.Length; i++) { if (types[i] == null) @@ -239,10 +237,8 @@ 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!!) { - if (member is null) throw new ArgumentNullException(nameof(member)); - const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; foreach (MemberInfo myMemberInfo in GetMembers(all)) { @@ -265,10 +261,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null); } @@ -300,12 +294,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (types == null) - throw new ArgumentNullException(nameof(types)); for (int i = 0; i < types.Length; i++) { if (types[i] == null) @@ -327,14 +317,11 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); if (genericParameterCount < 0) throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(genericParameterCount)); - if (types == null) - throw new ArgumentNullException(nameof(types)); + ArgumentNullException.ThrowIfNull(types); for (int i = 0; i < types.Length; i++) { if (types[i] == null) @@ -368,20 +355,16 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null); } @@ -395,12 +378,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (types == null) - throw new ArgumentNullException(nameof(types)); return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers); } @@ -431,11 +410,8 @@ public static RuntimeTypeHandle GetTypeHandle(object o) return type.TypeHandle; } - public static Type[] GetTypeArray(object[] args) + public static Type[] GetTypeArray(object[] args!!) { - if (args == null) - throw new ArgumentNullException(nameof(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 369d9df080cde5..8087c6024e645e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TypedReference.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TypedReference.cs @@ -14,12 +14,8 @@ namespace System public ref partial struct TypedReference { - public static TypedReference MakeTypedReference(object target, FieldInfo[] flds) + public static TypedReference MakeTypedReference(object target!!, FieldInfo[] flds!!) { - if (target == null) - throw new ArgumentNullException(nameof(target)); - if (flds == null) - throw new ArgumentNullException(nameof(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 12a2dce1d7258f..fe47b811905007 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UIntPtr.cs @@ -71,11 +71,8 @@ private unsafe UIntPtr(SerializationInfo info, StreamingContext context) _value = (void*)l; } - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) + void ISerializable.GetObjectData(SerializationInfo info!!, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(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 f3abc8aeae499c..897db7e0e735c4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/UnitySerializationHolder.cs @@ -31,14 +31,9 @@ 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 { - if (info == null) - { - throw new ArgumentNullException(nameof(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 43d3bb34b098ee..96da170cc6dd7a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Version.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Version.cs @@ -263,13 +263,8 @@ 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!!) { - if (input == null) - { - throw new ArgumentNullException(nameof(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 a2e5258f62b22c..a1517385593936 100644 --- a/src/libraries/System.Private.CoreLib/src/System/WeakReference.T.cs +++ b/src/libraries/System.Private.CoreLib/src/System/WeakReference.T.cs @@ -30,13 +30,8 @@ public WeakReference(T target, bool trackResurrection) Create(target, trackResurrection); } - private WeakReference(SerializationInfo info, StreamingContext context) + private WeakReference(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - T target = (T)info.GetValue("TrackedObject", typeof(T))!; // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) @@ -59,13 +54,8 @@ 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) { - if (info == null) - { - throw new ArgumentNullException(nameof(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 870221d5f2049b..759ef6d6f87821 100644 --- a/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs +++ b/src/libraries/System.Private.CoreLib/src/System/WeakReference.cs @@ -24,25 +24,16 @@ public WeakReference(object? target, bool trackResurrection) Create(target, trackResurrection); } - protected WeakReference(SerializationInfo info, StreamingContext context) + protected WeakReference(SerializationInfo info!!, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(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) { - if (info == null) - { - throw new ArgumentNullException(nameof(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/Json/JsonEncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs index 44b0bda31e9942..5b6c17ac947795 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs @@ -44,10 +44,7 @@ public JsonEncodingStreamWrapper(Stream stream, Encoding? encoding, bool isReade } else { - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } + ArgumentNullException.ThrowIfNull(encoding); InitForWriting(stream, encoding); } 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 1f83baca5a5410..c27cac95fbe2c3 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,13 +19,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(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 3e24e963d84f68..35280dd78abebe 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 @@ -732,10 +732,7 @@ public override int ReadValueAsBase64(byte[] buffer, int offset, int count) { if (IsAttributeValue) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative); @@ -763,10 +760,7 @@ public override int ReadValueChunk(char[] chars, int offset, int count) { if (IsAttributeValue) { - if (chars == null) - { - throw new ArgumentNullException(nameof(chars)); - } + ArgumentNullException.ThrowIfNull(chars); if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative); @@ -805,13 +799,9 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative); @@ -836,13 +826,9 @@ public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, X ResetState(); } - public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + public void SetInput(Stream stream!!, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } MoveToInitial(quotas, onClose); stream = new JsonEncodingStreamWrapper(stream, encoding, true); @@ -857,12 +843,8 @@ 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) { - if (array == null) - { - throw new ArgumentNullException(nameof(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 8ce76f7b50f282..86b1d98b0632f2 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 @@ -94,10 +94,7 @@ public XmlJsonWriter(bool indent, string? indentChars) _indent = indent; if (indent) { - if (indentChars == null) - { - throw new ArgumentNullException(nameof(indentChars)); - } + ArgumentNullException.ThrowIfNull(indentChars); _indentChars = indentChars; } InitializeWriter(); @@ -231,12 +228,8 @@ public override void Flush() _nodeWriter.Flush(); } - public override string? LookupPrefix(string ns) + public override string? LookupPrefix(string ns!!) { - if (ns == null) - { - throw new ArgumentNullException(nameof(ns)); - } if (ns == Globals.XmlnsNamespace) { return Globals.XmlnsPrefix; @@ -252,16 +245,8 @@ public override void Flush() return null; } - public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) + public void SetOutput(Stream stream!!, Encoding encoding!!, bool ownsStream) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - if (encoding == null) - { - throw new ArgumentNullException(nameof(encoding)); - } if (encoding.WebName != Encoding.UTF8.WebName) { stream = new JsonEncodingStreamWrapper(stream, encoding, false); @@ -379,13 +364,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -405,13 +385,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -441,13 +416,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -723,12 +693,8 @@ public override void WriteProcessingInstruction(string name, string? text) } } - public override void WriteQualifiedName(string localName, string? ns) + public override void WriteQualifiedName(string localName!!, string? ns) { - if (localName == null) - { - throw new ArgumentNullException(nameof(localName)); - } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); @@ -746,13 +712,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - // Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does. if (index < 0) { @@ -814,10 +775,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), nameof(ns)); } } - if (localName == null) - { - throw new ArgumentNullException(nameof(localName)); - } + ArgumentNullException.ThrowIfNull(localName); if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); @@ -899,12 +857,8 @@ public override void WriteStartDocument() } } - public override void WriteStartElement(string? prefix, string localName, string? ns) + public override void WriteStartElement(string? prefix, string localName!!, string? ns) { - if (localName == null) - { - throw new ArgumentNullException(nameof(localName)); - } if (localName.Length == 0) { throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName)); @@ -1096,29 +1050,19 @@ public override void WriteValue(TimeSpan value) _nodeWriter.WriteTimeSpanText(value); } - public override void WriteValue(UniqueId value) + public override void WriteValue(UniqueId value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - StartText(); _nodeWriter.WriteUniqueIdText(value); } - public override void WriteValue(object value) + public override void WriteValue(object value!!) { if (IsClosed) { ThrowClosed(); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (value is Array) { WriteValue((Array)value); @@ -1139,10 +1083,7 @@ public override void WriteWhitespace(string? ws) { ThrowClosed(); } - if (ws == null) - { - throw new ArgumentNullException(nameof(ws)); - } + ArgumentNullException.ThrowIfNull(ws); for (int i = 0; i < ws.Length; ++i) { @@ -1461,18 +1402,13 @@ private void WriteJsonQuote() _nodeWriter.WriteText(JsonGlobals.QuoteChar); } - private void WritePrimitiveValue(object value) + private void WritePrimitiveValue(object value!!) { if (IsClosed) { ThrowClosed(); } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (value is ulong) { WriteValue((ulong)value); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs index 2d2c21442d3647..be78f4037422be 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.cs @@ -24,8 +24,7 @@ public override int GetByteCount(char[] chars, int index, int count) public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { - if (chars == null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(chars); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); if (charIndex > chars.Length) @@ -34,8 +33,7 @@ public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative); if (charCount > chars.Length - charIndex) throw new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)); - if (bytes == null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(bytes); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); if (byteIndex > bytes.Length) @@ -68,8 +66,7 @@ public override int GetCharCount(byte[] bytes, int index, int count) public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { - if (bytes == null) - throw new ArgumentNullException(nameof(bytes)); + ArgumentNullException.ThrowIfNull(bytes); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); if (byteIndex > bytes.Length) @@ -79,8 +76,7 @@ public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, if (byteCount > bytes.Length - byteIndex) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)); int charCount = GetCharCount(bytes, byteIndex, byteCount); - if (chars == null) - throw new ArgumentNullException(nameof(chars)); + ArgumentNullException.ThrowIfNull(chars); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); if (charIndex > chars.Length) 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 564d053d678541..c6c6cf1f867a7c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs @@ -16,12 +16,8 @@ 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) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - if (encoding == null) - throw new ArgumentNullException(nameof(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 4b5d072e8ac43e..9de855fd4b59b7 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,10 +301,8 @@ public static string ObjectToString(object o) return o.ToString() ?? string.Empty; } - public static double GetDateValue(object dtv) + public static double GetDateValue(object dtv!!) { - if (dtv == null) - throw new ArgumentNullException(nameof(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 b69b12368f2aa1..f73d86d0c47993 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -362,11 +362,8 @@ 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(string uriString) + public Uri(string uriString!!) { - if (uriString is null) - throw new ArgumentNullException(nameof(uriString)); - CreateThis(uriString, false, UriKind.Absolute); DebugSetLeftCtor(); } @@ -377,11 +374,8 @@ public 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(string uriString, bool dontEscape) + public Uri(string uriString!!, bool dontEscape) { - if (uriString == null) - throw new ArgumentNullException(nameof(uriString)); - CreateThis(uriString, dontEscape, UriKind.Absolute); DebugSetLeftCtor(); } @@ -393,11 +387,8 @@ public Uri(string uriString, bool dontEscape) // 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) { - if (baseUri is null) - throw new ArgumentNullException(nameof(baseUri)); - if (!baseUri.IsAbsoluteUri) throw new ArgumentOutOfRangeException(nameof(baseUri)); @@ -408,11 +399,8 @@ public Uri(Uri baseUri, string? relativeUri, bool dontEscape) // // Uri(string, UriKind); // - public Uri(string uriString, UriKind uriKind) + public Uri(string uriString!!, UriKind uriKind) { - if (uriString is null) - throw new ArgumentNullException(nameof(uriString)); - CreateThis(uriString, false, uriKind); DebugSetLeftCtor(); } @@ -422,11 +410,8 @@ public Uri(string uriString, UriKind uriKind) /// /// A string that identifies the resource to be represented by the instance. /// Options that control how the is created and behaves. - public Uri(string uriString, in UriCreationOptions creationOptions) + public Uri(string uriString!!, in UriCreationOptions creationOptions) { - if (uriString is null) - throw new ArgumentNullException(nameof(uriString)); - CreateThis(uriString, false, UriKind.Absolute, in creationOptions); DebugSetLeftCtor(); } @@ -438,11 +423,8 @@ public Uri(string uriString, in UriCreationOptions creationOptions) // 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) { - if (baseUri is null) - throw new ArgumentNullException(nameof(baseUri)); - if (!baseUri.IsAbsoluteUri) throw new ArgumentOutOfRangeException(nameof(baseUri)); @@ -540,11 +522,8 @@ 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) { - if (baseUri is null) - throw new ArgumentNullException(nameof(baseUri)); - if (!baseUri.IsAbsoluteUri) throw new ArgumentOutOfRangeException(nameof(baseUri)); @@ -1774,11 +1753,8 @@ 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!!) { - if (uri is null) - throw new ArgumentNullException(nameof(uri)); - if (IsNotAbsoluteUri || uri.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 da3cf9f398b0d4..ab726f0cac9850 100644 --- a/src/libraries/System.Private.Uri/src/System/UriBuilder.cs +++ b/src/libraries/System.Private.Uri/src/System/UriBuilder.cs @@ -38,9 +38,9 @@ public UriBuilder(string uri) SetFieldsFromUri(); } - public UriBuilder(Uri uri) + public UriBuilder(Uri uri!!) { - _uri = uri ?? throw new ArgumentNullException(nameof(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 799f9ca2d577f9..ef15c1f4471ddc 100644 --- a/src/libraries/System.Private.Uri/src/System/UriExt.cs +++ b/src/libraries/System.Private.Uri/src/System/UriExt.cs @@ -554,11 +554,8 @@ internal unsafe bool InternalIsWellFormedOriginalString() return true; } - public static string UnescapeDataString(string stringToUnescape) + public static string UnescapeDataString(string stringToUnescape!!) { - if (stringToUnescape is null) - throw new ArgumentNullException(nameof(stringToUnescape)); - if (stringToUnescape.Length == 0) return string.Empty; @@ -855,11 +852,8 @@ internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFo } } - public bool IsBaseOf(Uri uri) + public bool IsBaseOf(Uri uri!!) { - if (uri is null) - throw new ArgumentNullException(nameof(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 660d15d49ade4f..d436263440255a 100644 --- a/src/libraries/System.Private.Uri/src/System/UriHelper.cs +++ b/src/libraries/System.Private.Uri/src/System/UriHelper.cs @@ -111,13 +111,9 @@ 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') { - if (stringToEscape is null) - { - throw new ArgumentNullException(nameof(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 7c39a6c44a336e..d23e6f1f677622 100644 --- a/src/libraries/System.Private.Uri/src/System/UriScheme.cs +++ b/src/libraries/System.Private.Uri/src/System/UriScheme.cs @@ -163,14 +163,8 @@ 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) { - if (uriParser == null) - throw new ArgumentNullException(nameof(uriParser)); - - if (schemeName == null) - throw new ArgumentNullException(nameof(schemeName)); - if (schemeName.Length == 1) throw new ArgumentOutOfRangeException(nameof(schemeName)); @@ -187,11 +181,8 @@ public static void Register(UriParser uriParser, string schemeName, int defaultP // // Is a Uri scheme known to System.Uri? // - public static bool IsKnownScheme(string schemeName) + public static bool IsKnownScheme(string schemeName!!) { - if (schemeName == null) - throw new ArgumentNullException(nameof(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 024823a9141369..f3c86d6ea74905 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,9 +21,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetAttributes(source, null); } @@ -37,9 +36,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetAttributes(source, name) : XAttribute.EmptySequence; } @@ -53,9 +51,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetAncestors(source, null, false); } @@ -69,9 +66,8 @@ public static IEnumerable Ancestors(this IEnumerable source) wh /// 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetAncestors(source, name, false) : XElement.EmptySequence; } @@ -87,9 +83,8 @@ public static IEnumerable Ancestors(this IEnumerable source, XN /// This is done for each in this of /// . /// - public static IEnumerable AncestorsAndSelf(this IEnumerable source) + public static IEnumerable AncestorsAndSelf(this IEnumerable source!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetAncestors(source, null, true); } @@ -105,18 +100,16 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return NodesIterator(source); } @@ -142,9 +135,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendantNodes(source, false); } @@ -158,9 +150,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendants(source, null, false); } @@ -174,9 +165,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetDescendants(source, name, false) : XElement.EmptySequence; } @@ -192,9 +182,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendantNodes(source, true); } @@ -210,9 +199,8 @@ public static IEnumerable DescendantNodesAndSelf(this IEnumerable in this /// of . /// - public static IEnumerable DescendantsAndSelf(this IEnumerable source) + public static IEnumerable DescendantsAndSelf(this IEnumerable source!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendants(source, null, true); } @@ -228,9 +216,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetDescendants(source, name, true) : XElement.EmptySequence; } @@ -242,9 +229,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return GetElements(source, null); } @@ -256,9 +242,8 @@ public static IEnumerable Elements(this IEnumerable source) whe /// 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 { - if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetElements(source, name) : XElement.EmptySequence; } @@ -271,9 +256,8 @@ public static IEnumerable Elements(this IEnumerable source, XNa /// 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? { - if (source == null) throw new ArgumentNullException(nameof(source)); return DocumentOrderIterator(source); } @@ -293,10 +277,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); - int count; XAttribute?[] attributes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) @@ -311,10 +293,8 @@ 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 { - if (source == null) throw new ArgumentNullException(nameof(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 d86a6cb380a7b1..94166f12d7a009 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,10 +51,8 @@ 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!!) { - if (name == null) throw new ArgumentNullException(nameof(name)); - if (value == null) throw new ArgumentNullException(nameof(value)); string s = XContainer.GetStringValue(value); ValidateAttribute(name, s); this.name = name; @@ -69,9 +67,8 @@ public XAttribute(XName name, object value) /// /// Thrown if the specified is null. /// - public XAttribute(XAttribute other) + public XAttribute(XAttribute other!!) { - if (other == null) throw new ArgumentNullException(nameof(other)); name = other.name; value = other.value; } @@ -194,9 +191,8 @@ public void Remove() /// /// Thrown if the specified value is null. /// - public void SetValue(object value) + public void SetValue(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); Value = XContainer.GetStringValue(value); } @@ -248,9 +244,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); } @@ -284,9 +279,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToInt32(attribute.value); } @@ -320,9 +314,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToUInt32(attribute.value); } @@ -356,9 +349,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToInt64(attribute.value); } @@ -392,9 +384,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToUInt64(attribute.value); } @@ -428,9 +419,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToSingle(attribute.value); } @@ -464,9 +454,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToDouble(attribute.value); } @@ -500,9 +489,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToDecimal(attribute.value); } @@ -536,9 +524,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); } @@ -572,9 +559,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToDateTimeOffset(attribute.value); } @@ -608,9 +594,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(attribute)); return XmlConvert.ToTimeSpan(attribute.value); } @@ -644,9 +629,8 @@ 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!!) { - if (attribute == null) throw new ArgumentNullException(nameof(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 7c85fb89e6c183..1110a474ac29e3 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,9 +45,8 @@ public override XmlNodeType NodeType /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteCData(text); } @@ -63,10 +62,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(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 dbb8ba0f9108a1..53975caeac8238 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,9 +26,8 @@ public class XComment : XNode /// /// Thrown if the specified value is null. /// - public XComment(string value) + public XComment(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); this.value = value; } @@ -36,9 +35,8 @@ 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!!) { - if (other == null) throw new ArgumentNullException(nameof(other)); this.value = other.value; } @@ -89,9 +87,8 @@ public string Value /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteComment(value); } @@ -102,10 +99,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(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 2d98ae02585d9f..49c782a3245fe1 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,9 +26,8 @@ public abstract class XContainer : XNode internal XContainer() { } - internal XContainer(XContainer other) + internal XContainer(XContainer other!!) { - if (other == null) throw new ArgumentNullException(nameof(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 8407f48b9ed198..52c1f5ce5d04d2 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,9 +48,8 @@ public XDeclaration(string? version, string? encoding, string? standalone) /// /// The used to initialize this object. /// - public XDeclaration(XDeclaration other) + public XDeclaration(XDeclaration other!!) { - if (other == null) throw new ArgumentNullException(nameof(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 9afbc2ba9431e3..189d89a294bd6a 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 @@ -418,9 +418,8 @@ 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) { - if (reader == null) throw new ArgumentNullException(nameof(reader)); if (reader.ReadState == ReadState.Initial) reader.Read(); XDocument d = InitLoad(reader, options); @@ -449,10 +448,8 @@ 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) { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return LoadAsyncInternal(reader, options, cancellationToken); @@ -791,9 +788,8 @@ 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!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); if (_declaration != null && _declaration.Standalone == "yes") { writer.WriteStartDocument(true); @@ -820,10 +816,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(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 f9605ca14eddfa..3b422190e91e3c 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,9 +33,8 @@ 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!!) { - if (other == null) throw new ArgumentNullException(nameof(other)); _name = other._name; _publicId = other._publicId; _systemId = other._systemId; @@ -140,9 +139,8 @@ public string? SystemId /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteDocType(_name, _publicId, _systemId, _internalSubset); } @@ -155,10 +153,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(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 311a4855daa3e6..e0291deff59d0d 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 @@ -125,9 +125,8 @@ public XElement(XElement other) /// The object whose value will be used /// to initialize the new element. /// - public XElement(XStreamingElement other) + public XElement(XStreamingElement other!!) { - if (other == null) throw new ArgumentNullException(nameof(other)); name = other.name; AddContentSkipNotify(other.content); } @@ -802,9 +801,8 @@ 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) { - if (reader == null) throw new ArgumentNullException(nameof(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(); @@ -829,10 +827,8 @@ 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) { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return LoadAsyncInternal(reader, options, cancellationToken); @@ -1155,9 +1151,8 @@ 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!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteStartDocument(); WriteTo(writer); writer.WriteEndDocument(); @@ -1170,10 +1165,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(writer)); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return SaveAsyncInternal(writer, cancellationToken); @@ -1281,9 +1274,8 @@ public void SetElementValue(XName name, object? value) /// /// Thrown if the specified value is null. /// - public void SetValue(object value) + public void SetValue(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); Value = GetStringValue(value); } @@ -1293,9 +1285,8 @@ public void SetValue(object value) /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); new ElementWriter(writer).WriteElement(this); } @@ -1306,10 +1297,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(writer)); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return new ElementWriter(writer).WriteElementAsync(this, cancellationToken); @@ -1354,9 +1343,8 @@ public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellati /// Thrown if the specified element is null. /// [CLSCompliant(false)] - public static explicit operator bool(XElement element) + public static explicit operator bool(XElement element!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToBoolean(element.Value.ToLowerInvariant()); } @@ -1396,9 +1384,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToInt32(element.Value); } @@ -1438,9 +1425,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToUInt32(element.Value); } @@ -1480,9 +1466,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToInt64(element.Value); } @@ -1522,9 +1507,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToUInt64(element.Value); } @@ -1564,9 +1548,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToSingle(element.Value); } @@ -1606,9 +1589,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToDouble(element.Value); } @@ -1648,9 +1630,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToDecimal(element.Value); } @@ -1690,9 +1671,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return DateTime.Parse(element.Value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); } @@ -1732,9 +1712,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToDateTimeOffset(element.Value); } @@ -1774,9 +1753,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToTimeSpan(element.Value); } @@ -1816,9 +1794,8 @@ 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!!) { - if (element == null) throw new ArgumentNullException(nameof(element)); return XmlConvert.ToGuid(element.Value); } @@ -1857,9 +1834,8 @@ public static explicit operator Guid(XElement element) /// The stream from which the /// is deserialized. /// - void IXmlSerializable.ReadXml(XmlReader reader) + void IXmlSerializable.ReadXml(XmlReader reader!!) { - if (reader == null) throw new ArgumentNullException(nameof(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 d7e0a5130e72b1..f0036a576622b0 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,9 +53,8 @@ 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!!) { - if (localName == null) throw new ArgumentNullException(nameof(localName)); return GetName(localName, 0, localName.Length); } @@ -112,9 +111,8 @@ 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!!) { - if (namespaceName == null) throw new ArgumentNullException(nameof(namespaceName)); return Get(namespaceName, 0, namespaceName.Length); } 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 389b9dc5767149..5c22fa17b53cd9 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,9 +438,8 @@ 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!!) { - if (reader == null) throw new ArgumentNullException(nameof(reader)); if (reader.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); switch (reader.NodeType) { @@ -475,10 +474,8 @@ 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) { - if (reader == null) - throw new ArgumentNullException(nameof(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/XNodeBuilder.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs index 4e4164c04c326a..18260645a7773f 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs @@ -165,7 +165,7 @@ public override void WriteRaw(string data) public override void WriteStartAttribute(string? prefix, string localName, string? namespaceName) { - if (prefix == null) throw new ArgumentNullException(nameof(prefix)); + ArgumentNullException.ThrowIfNull(prefix); _attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName!).GetName(localName); _attrValue = string.Empty; } 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 1855419be7db42..8f817dc4085626 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,9 +77,8 @@ 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!!) { - if (annotation == null) throw new ArgumentNullException(nameof(annotation)); if (annotations == null) { annotations = annotation is object[]? new object[] { annotation } : annotation; 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 4218332977c11d..dddb5f1c9566d1 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,9 +26,8 @@ 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!!) { - if (data == null) throw new ArgumentNullException(nameof(data)); ValidateName(target); this.target = target; this.data = data; @@ -39,9 +38,8 @@ 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!!) { - if (other == null) throw new ArgumentNullException(nameof(other)); this.target = other.target; this.data = other.data; } @@ -115,9 +113,8 @@ public string Target /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteProcessingInstruction(target, data); } @@ -128,10 +125,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(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 4e9373f031b1c6..a8a89e4eafadf2 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 @@ -153,9 +153,8 @@ 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!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteStartDocument(); WriteTo(writer); writer.WriteEndDocument(); @@ -214,9 +213,8 @@ public string ToString(SaveOptions options) /// Write this to an /// /// - public void WriteTo(XmlWriter writer) + public void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(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 fa85a690bb66cd..65295605104a3e 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,9 +18,8 @@ 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!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); text = value; } @@ -28,9 +27,8 @@ 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!!) { - if (other == null) throw new ArgumentNullException(nameof(other)); text = other.text; } @@ -78,9 +76,8 @@ public string Value /// /// The to write this to. /// - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) throw new ArgumentNullException(nameof(writer)); if (parent is XDocument) { writer.WriteWhitespace(text); @@ -100,10 +97,8 @@ 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) { - if (writer == null) - throw new ArgumentNullException(nameof(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 a1c1b986df663c..752409ce7f6764 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,9 +441,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return source.Annotation(); } @@ -451,9 +450,8 @@ 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!!) { - if (source == null) throw new ArgumentNullException(nameof(source)); return source.Annotation(); } @@ -481,10 +479,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (schemas == null) throw new ArgumentNullException(nameof(schemas)); new XNodeValidator(schemas, validationEventHandler).Validate(source, null, addSchemaInfo); } @@ -518,11 +514,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (partialValidationType == null) throw new ArgumentNullException(nameof(partialValidationType)); - if (schemas == null) throw new ArgumentNullException(nameof(schemas)); new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo); } @@ -556,11 +549,8 @@ 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) { - if (source == null) throw new ArgumentNullException(nameof(source)); - if (partialValidationType == null) throw new ArgumentNullException(nameof(partialValidationType)); - if (schemas == null) throw new ArgumentNullException(nameof(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 8460c3345330c9..1476e69449d0b5 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,9 +922,8 @@ 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) { - if (node == null) throw new ArgumentNullException(nameof(node)); if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType)); XText? text = node as XText; if (text != null) @@ -956,9 +955,8 @@ 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) { - if (node == null) throw new ArgumentNullException(nameof(node)); return default(XPathEvaluator).Evaluate(node, expression, resolver); } @@ -1005,9 +1003,8 @@ 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) { - if (node == null) throw new ArgumentNullException(nameof(node)); return (IEnumerable)default(XPathEvaluator).Evaluate(node, expression, resolver); } 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 e7ec9664f1939b..6588b4f0e05284 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs @@ -42,12 +42,8 @@ internal override bool IsFull } } - internal override int Decode(char[] chars, int startPos, int len) + internal override int Decode(char[] chars!!, int startPos, int len) { - if (chars == null) - { - throw new ArgumentNullException(nameof(chars)); - } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); @@ -72,12 +68,8 @@ 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) { - if (str == null) - { - throw new ArgumentNullException(nameof(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 18d72d4778367e..7b1818693a2d2c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs @@ -22,12 +22,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(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 233b1a5044a39d..27012a54afeb9d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs @@ -12,12 +12,8 @@ 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 async Task EncodeAsync(byte[] buffer!!, int index, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); 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 9bacf94038822e..c22d4bd723f5cd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs @@ -37,12 +37,8 @@ internal override bool IsFull } } - internal override int Decode(char[] chars, int startPos, int len) + internal override int Decode(char[] chars!!, int startPos, int len) { - if (chars == null) - { - throw new ArgumentNullException(nameof(chars)); - } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); @@ -69,12 +65,8 @@ 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) { - if (str == null) - { - throw new ArgumentNullException(nameof(str)); - } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); @@ -124,13 +116,8 @@ internal override void SetNextOutputBuffer(Array buffer, int index, int count) // // Static methods // - public static byte[] Decode(char[] chars, bool allowOddChars) + public static byte[] Decode(char[] chars!!, bool allowOddChars) { - if (chars == null) - { - throw new ArgumentNullException(nameof(chars)); - } - int len = chars.Length; if (len == 0) { 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 397b48adc6111e..77bd6d1ea9e3e0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs @@ -7,12 +7,8 @@ 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) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(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 9a84f5f9829133..dcf46e3bccecba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs @@ -7,12 +7,8 @@ namespace System.Xml { internal static partial class BinHexEncoder { - internal static async Task EncodeAsync(byte[] buffer, int index, int count, XmlWriter writer) + internal static async Task EncodeAsync(byte[] buffer!!, int index, int count, XmlWriter writer) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); 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 80c4ab6d2df75e..dcab10a76dfe8a 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,10 +60,8 @@ 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) { - if (namespaceURI == null) throw new ArgumentNullException(nameof(namespaceURI)); - _localName = parent.NameTable.Get(name); _namespaceUri = namespaceURI; } @@ -173,10 +171,8 @@ 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) { - if (namespaceURI == null) throw new ArgumentNullException(nameof(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 99ca6edc3049af..b268b803637659 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,13 +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 - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); 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 b0e5d48b2d6967..99f5fef57012fb 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 @@ -1656,10 +1656,8 @@ 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); @@ -1686,10 +1684,8 @@ 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); @@ -1725,10 +1721,8 @@ 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 68adf4d128807b..8280e0201088ca 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,10 +340,8 @@ 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 @@ -363,10 +361,8 @@ internal XmlReader CreateReader(Stream input, Uri? baseUri, string? baseUriStrin 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 @@ -386,10 +382,8 @@ internal XmlReader CreateReader(TextReader input, string? baseUriString, XmlPars 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/XmlWriterSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs index 11492a32b99786..bd0afc62a28440 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,10 +332,8 @@ 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) @@ -360,10 +358,8 @@ internal XmlWriter CreateWriter(string outputFileName) } } - internal XmlWriter CreateWriter(Stream output) + internal XmlWriter CreateWriter(Stream output!!) { - ArgumentNullException.ThrowIfNull(output); - XmlWriter writer; // create raw writer @@ -435,10 +431,8 @@ 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 @@ -481,10 +475,8 @@ 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 84d4fa56c28805..12177d2e64c563 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,13 +38,8 @@ public override XPathNavigator Clone() return new DocumentXPathNavigator(this); } - public override void SetValue(string value) + public override void SetValue(string value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 ade3ad8fbfdd8b..e9e24dcc41fed1 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,13 +1133,8 @@ public class XmlNodeReader : XmlReader, IXmlNamespaceResolver // Creates an instance of the XmlNodeReader class using the specified XmlNode. - public XmlNodeReader(XmlNode node) + public XmlNodeReader(XmlNode node!!) { - if (node == null) - { - throw new ArgumentNullException(nameof(node)); - } - _readerNav = new XmlNodeReaderNavigator(node); _curDepth = 0; 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 e2d7fb2dfa0cc6..0f8e6d52b5b97c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -51,13 +51,8 @@ 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!!) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - int len = key.Length; if (len == 0) { @@ -118,13 +113,8 @@ 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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 1ee3949536b803..6408718f2bc2b1 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 @@ -285,30 +285,13 @@ 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!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(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) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); @@ -325,16 +308,8 @@ 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!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } if (value.CanSeek) { // stream of known length -> allocate the byte array and read all data into it @@ -360,16 +335,8 @@ public void Add(Uri uri, Stream value) } } - public void Add(Uri uri, string value) + public void Add(Uri uri!!, string value!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } Add(uri, new StringData(value)); } 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 78685724522bdb..0fc3a11bc99e84 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 @@ -1040,14 +1040,9 @@ 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) { Exception? exception; - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - string? s = value as string; typedValue = null; if (s != null) @@ -1304,13 +1299,9 @@ 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) { Exception? exception; - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } typedValue = null; string? s = value as string; if (s != null) @@ -3822,10 +3813,8 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa { throw new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } - if (nsmgr == null) - { - throw new ArgumentNullException(nameof(nsmgr)); - } + ArgumentNullException.ThrowIfNull(nsmgr); + string prefix; try { 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 33847d7040ea67..fdcdb6438cb4e7 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 @@ -177,12 +177,8 @@ 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) { - if (instanceDocument == null) - { - throw new ArgumentNullException(nameof(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 939862db6b2edd..0581ab222c6484 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,58 +78,49 @@ public IDictionary GetNamespacesInScope(XmlNamespaceScope scope) // XmlAtomicValue constructors and methods //----------------------------------------------- - internal XmlAtomicValue(XmlSchemaType xmlType, bool value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, bool value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Boolean; _unionVal.boolVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, DateTime value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, DateTime value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.DateTime; _unionVal.dtVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, double value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, double value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Double; _unionVal.dblVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, int value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, int value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Int32; _unionVal.i32Val = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, long value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, long value) { - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _clrType = TypeCode.Int64; _unionVal.i64Val = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, string value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, string value, IXmlNamespaceResolver? nsResolver) + internal XmlAtomicValue(XmlSchemaType xmlType!!, string value!!, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; if (nsResolver != null && (_xmlType.TypeCode == XmlTypeCode.QName || _xmlType.TypeCode == XmlTypeCode.Notation)) @@ -139,18 +130,14 @@ internal XmlAtomicValue(XmlSchemaType xmlType, string value, IXmlNamespaceResolv } } - internal XmlAtomicValue(XmlSchemaType xmlType, object value) + internal XmlAtomicValue(XmlSchemaType xmlType!!, object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _xmlType = xmlType; _objVal = value; } - internal XmlAtomicValue(XmlSchemaType xmlType, object value, IXmlNamespaceResolver? nsResolver) + internal XmlAtomicValue(XmlSchemaType xmlType!!, object value!!, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (xmlType == null) throw new ArgumentNullException(nameof(xmlType)); _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 6b75f550f00c83..c1d9664e985c85 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 @@ -42,13 +42,8 @@ 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!!) { - if (nametable == null) - { - throw new ArgumentNullException(nameof(nametable)); - } - _nameTable = nametable; _collection = Hashtable.Synchronized(new Hashtable()); _xmlResolver = null; @@ -126,10 +121,8 @@ 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) { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); XmlNameTable readerNameTable = reader.NameTable; SchemaInfo schemaInfo = new SchemaInfo(); @@ -162,11 +155,8 @@ internal XmlResolver? XmlResolver return Add(schema, _xmlResolver); } - public XmlSchema? Add(XmlSchema schema, XmlResolver? resolver) + public XmlSchema? Add(XmlSchema schema!!, XmlResolver? resolver) { - if (schema == null) - throw new ArgumentNullException(nameof(schema)); - SchemaInfo schemaInfo = new SchemaInfo(); schemaInfo.SchemaType = SchemaType.XSD; return Add(schema.TargetNamespace, schemaInfo, schema, true, resolver); @@ -176,10 +166,8 @@ 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!!) { - if (schema == null) - throw new ArgumentNullException(nameof(schema)); if (this == schema) return; IDictionaryEnumerator enumerator = schema._collection.GetEnumerator(); @@ -203,13 +191,8 @@ public XmlSchema? this[string? ns] } } - public bool Contains(XmlSchema schema) + public bool Contains(XmlSchema schema!!) { - if (schema == null) - { - throw new ArgumentNullException(nameof(schema)); - } - return this[schema.TargetNamespace] != null; } @@ -231,10 +214,8 @@ public XmlSchemaCollectionEnumerator GetEnumerator() return new XmlSchemaCollectionEnumerator(_collection); } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();) @@ -247,10 +228,8 @@ void ICollection.CopyTo(Array array, int index) } } - public void CopyTo(XmlSchema[] array, int index) + public void CopyTo(XmlSchema[] array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(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 fc4806a095920d..0d09a2f0994180 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,33 +23,13 @@ public abstract class XmlSchemaDatatype internal XmlSchemaDatatype() { } - public virtual object ChangeType(object value, Type targetType) + public virtual object ChangeType(object value!!, Type targetType!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (targetType == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - if (namespaceResolver == null) - { - throw new ArgumentNullException(nameof(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 54693372418579..62ee7612bb5bf0 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,11 +186,8 @@ public bool IsSynchronized } } - public void CopyTo(Array array, int arrayIndex) + public void CopyTo(Array array!!, int arrayIndex) { - if (array == null) - throw new ArgumentNullException(nameof(array)); - if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); @@ -241,11 +238,8 @@ public bool IsSynchronized } } - public void CopyTo(Array array, int arrayIndex) + public void CopyTo(Array array!!, int arrayIndex) { - if (array == null) - throw new ArgumentNullException(nameof(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 50ba298672844c..3e408b36555ac5 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,13 +84,8 @@ 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!!) { - if (nameTable == null) - { - throw new ArgumentNullException(nameof(nameTable)); - } - _nameTable = nameTable; _schemas = new SortedList(); @@ -324,12 +319,8 @@ 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!!) { - if (schemaDocument == null) - { - throw new ArgumentNullException(nameof(schemaDocument)); - } if (targetNamespace != null) { targetNamespace = XmlComplianceUtil.CDataNormalize(targetNamespace); @@ -358,12 +349,8 @@ 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!!) { - if (schemas == null) - { - throw new ArgumentNullException(nameof(schemas)); - } if (this == schemas) { return; @@ -444,12 +431,8 @@ public void Add(XmlSchemaSet schemas) } } - public XmlSchema? Add(XmlSchema schema) + public XmlSchema? Add(XmlSchema schema!!) { - if (schema == null) - { - throw new ArgumentNullException(nameof(schema)); - } lock (InternalSyncObject) { if (_schemas.ContainsKey(schema.SchemaId)) @@ -466,12 +449,8 @@ public void Add(XmlSchemaSet schemas) return Remove(schema, true); } - public bool RemoveRecursive(XmlSchema schemaToRemove) + public bool RemoveRecursive(XmlSchema schemaToRemove!!) { - if (schemaToRemove == null) - { - throw new ArgumentNullException(nameof(schemaToRemove)); - } if (!_schemas.ContainsKey(schemaToRemove.SchemaId)) { return false; @@ -549,12 +528,8 @@ public bool Contains(string? targetNamespace) return _targetNamespaces[targetNamespace] != null; } - public bool Contains(XmlSchema schema) + public bool Contains(XmlSchema schema!!) { - if (schema == null) - { - throw new ArgumentNullException(nameof(schema)); - } return _schemas.ContainsValue(schema); } @@ -653,17 +628,13 @@ public void Compile() return; } - public XmlSchema Reprocess(XmlSchema schema) + public XmlSchema Reprocess(XmlSchema 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: // foreach (XmlSchema s in schemaset.schemas) { schemaset.Reprocess(s); } // This is by purpose. - if (schema == null) - { - throw new ArgumentNullException(nameof(schema)); - } if (!_schemas.ContainsKey(schema.SchemaId)) { throw new ArgumentException(SR.Sch_SchemaDoesNotExist, nameof(schema)); @@ -744,10 +715,8 @@ public XmlSchema Reprocess(XmlSchema schema) } } - public void CopyTo(XmlSchema[] schemas, int index) + public void CopyTo(XmlSchema[] schemas!!, int index) { - if (schemas == null) - throw new ArgumentNullException(nameof(schemas)); if (index < 0 || index > schemas.Length - 1) throw new ArgumentOutOfRangeException(nameof(index)); _schemas.Values.CopyTo(schemas, index); @@ -877,12 +846,8 @@ 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) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } if (targetNamespace == null) { targetNamespace = string.Empty; @@ -1115,15 +1080,10 @@ private void ResolveSubstitutionGroup(XmlSchemaSubstitutionGroup substitutionGro substitutionGroup.Members.Add(headElement); } - internal XmlSchema? Remove(XmlSchema schema, bool forceCompile) + internal XmlSchema? Remove(XmlSchema schema!!, bool forceCompile) { // 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. - if (schema == null) - { - throw new ArgumentNullException(nameof(schema)); - } - lock (InternalSyncObject) { //Need to lock here so that remove cannot be called while the set is being compiled if (_schemas.ContainsKey(schema.SchemaId)) 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 e02e6af5fe8597..acc7db3b6aa51a 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,21 +159,8 @@ 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) { - if (nameTable == null) - { - throw new ArgumentNullException(nameof(nameTable)); - } - if (schemas == null) - { - throw new ArgumentNullException(nameof(schemas)); - } - if (namespaceResolver == null) - { - throw new ArgumentNullException(nameof(namespaceResolver)); - } - _nameTable = nameTable; _nsResolver = namespaceResolver; _validationFlags = validationFlags; @@ -328,12 +315,8 @@ public event ValidationEventHandler? ValidationEventHandler } //Methods - public void AddSchema(XmlSchema schema) + public void AddSchema(XmlSchema schema!!) { - if (schema == null) - { - throw new ArgumentNullException(nameof(schema)); - } if ((_validationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) == 0) { //Do not process schema if processInlineSchema is not set return; @@ -418,17 +401,8 @@ 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) { - if (localName == null) - { - throw new ArgumentNullException(nameof(localName)); - } - if (namespaceUri == null) - { - throw new ArgumentNullException(nameof(namespaceUri)); - } - CheckStateTransition(ValidatorState.Element, s_methodNames[(int)ValidatorState.Element]); ClearPSVI(); @@ -507,37 +481,18 @@ public void ValidateElement(string localName, string namespaceUri, XmlSchemaInfo } } - public object? ValidateAttribute(string localName, string namespaceUri, string attributeValue, XmlSchemaInfo? schemaInfo) + public object? ValidateAttribute(string localName, string namespaceUri, string attributeValue!!, XmlSchemaInfo? schemaInfo) { - if (attributeValue == null) - { - throw new ArgumentNullException(nameof(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) { - if (attributeValue == null) - { - throw new ArgumentNullException(nameof(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) { - if (localName == null) - { - throw new ArgumentNullException(nameof(localName)); - } - if (namespaceUri == null) - { - throw new ArgumentNullException(nameof(namespaceUri)); - } - ValidatorState toState = _validationStack.Length > 1 ? ValidatorState.Attribute : ValidatorState.TopLevelAttribute; CheckStateTransition(toState, s_methodNames[(int)toState]); @@ -744,13 +699,8 @@ public void ValidateElement(string localName, string namespaceUri, XmlSchemaInfo return typedVal; } - public void GetUnspecifiedDefaultAttributes(ArrayList defaultAttributes) + public void GetUnspecifiedDefaultAttributes(ArrayList defaultAttributes!!) { - if (defaultAttributes == null) - { - throw new ArgumentNullException(nameof(defaultAttributes)); - } - CheckStateTransition(ValidatorState.Attribute, "GetUnspecifiedDefaultAttributes"); GetUnspecifiedDefaultAttributes(defaultAttributes, false); } @@ -771,21 +721,13 @@ public void ValidateEndOfAttributes(XmlSchemaInfo? schemaInfo) } } - public void ValidateText(string elementValue) + public void ValidateText(string elementValue!!) { - if (elementValue == null) - { - throw new ArgumentNullException(nameof(elementValue)); - } ValidateText(elementValue, null); } - public void ValidateText(XmlValueGetter elementValue) + public void ValidateText(XmlValueGetter elementValue!!) { - if (elementValue == null) - { - throw new ArgumentNullException(nameof(elementValue)); - } ValidateText(null, elementValue); } @@ -854,22 +796,13 @@ private void ValidateText(string? elementStringValue, XmlValueGetter? elementVal } } - public void ValidateWhitespace(string elementValue) + public void ValidateWhitespace(string elementValue!!) { - if (elementValue == null) - { - throw new ArgumentNullException(nameof(elementValue)); - } ValidateWhitespace(elementValue, null); } - public void ValidateWhitespace(XmlValueGetter elementValue) + public void ValidateWhitespace(XmlValueGetter elementValue!!) { - if (elementValue == null) - { - throw new ArgumentNullException(nameof(elementValue)); - } - ValidateWhitespace(null, elementValue); } @@ -928,12 +861,8 @@ 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!!) { - if (typedValue == null) - { - throw new ArgumentNullException(nameof(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 3dd143e7b24dd0..a21884a23e9585 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,17 +874,13 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLNUMERIC10CONVERTER - public override decimal ToDecimal(string value) + public override decimal ToDecimal(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(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!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DecimalType) return ((decimal)value); @@ -899,17 +895,13 @@ public override int ToInt32(long value) { return Int64ToInt32((long)value); } - public override int ToInt32(string value) + public override int ToInt32(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(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!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt32((decimal)value); @@ -924,17 +916,13 @@ public override long ToInt64(int value) { return ((long)(int)value); } - public override long ToInt64(string value) + public override long ToInt64(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(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!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DecimalType) return DecimalToInt64((decimal)value); @@ -971,10 +959,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DecimalType) return this.ToString((decimal)value); @@ -1036,9 +1022,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1052,9 +1037,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); Type sourceType = value.GetType(); @@ -1140,17 +1124,13 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLNUMERIC2CONVERTER - public override double ToDouble(string value) + public override double ToDouble(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(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!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((double)value); @@ -1184,17 +1164,13 @@ public override float ToSingle(double value) { return ((float)(double)value); } - public override float ToSingle(string value) + public override float ToSingle(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(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!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DoubleType) return ((float)(double)value); @@ -1220,10 +1196,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DoubleType) return this.ToString((double)value); @@ -1253,11 +1227,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DoubleType) return this.ToDouble((string)value); if (destinationType == SingleType) return this.ToSingle((string)value); @@ -1268,11 +1239,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1317,10 +1285,8 @@ public override DateTime ToDateTime(DateTimeOffset value) return DateTimeOffsetToDateTime(value); } - public override DateTime ToDateTime(string value) + public override DateTime ToDateTime(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return TypeCode switch { XmlTypeCode.Date => StringToDate((string)value), @@ -1333,10 +1299,8 @@ public override DateTime ToDateTime(string value) _ => StringToDateTime((string)value), }; } - public override DateTime ToDateTime(object value) + public override DateTime ToDateTime(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ((DateTime)value); @@ -1356,10 +1320,8 @@ public override DateTimeOffset ToDateTimeOffset(DateTime value) return new DateTimeOffset(value); } - public override DateTimeOffset ToDateTimeOffset(string value) + public override DateTimeOffset ToDateTimeOffset(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return TypeCode switch { XmlTypeCode.Date => StringToDateOffset((string)value), @@ -1373,10 +1335,8 @@ public override DateTimeOffset ToDateTimeOffset(string value) }; } - public override DateTimeOffset ToDateTimeOffset(object value) + public override DateTimeOffset ToDateTimeOffset(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DateTimeType) return ToDateTimeOffset((DateTime)value); @@ -1452,10 +1412,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == DateTimeType) return this.ToString((DateTime)value); @@ -1485,11 +1443,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == DateTimeType) return this.ToDateTime((string)value); if (destinationType == DateTimeOffsetType) return this.ToDateTimeOffset((string)value); @@ -1500,11 +1455,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1543,16 +1495,12 @@ public static XmlValueConverter Create(XmlSchemaType schemaType) } #region AUTOGENERATED_XMLBOOLEANCONVERTER - public override bool ToBoolean(string value) + public override bool ToBoolean(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToBoolean((string)value); } - public override bool ToBoolean(object value) + public override bool ToBoolean(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == BooleanType) return ((bool)value); @@ -1613,10 +1561,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); @@ -1644,11 +1590,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == StringType) return ((string)value); @@ -1658,11 +1601,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1698,10 +1638,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == ByteArrayType) @@ -1740,11 +1678,8 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) // ChangeType //----------------------------------------------- - public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == ByteArrayType) { @@ -1778,11 +1713,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -1927,10 +1859,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return ((string)value); @@ -1944,11 +1874,8 @@ public override string ToString(object value, IXmlNamespaceResolver? nsResolver) // ChangeType //----------------------------------------------- - public override object ChangeType(string value, Type destinationType, IXmlNamespaceResolver? nsResolver) + public override object ChangeType(string value!!, Type destinationType!!, IXmlNamespaceResolver? nsResolver) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == StringType) return ((string)value); if (destinationType == XmlAtomicValueType) return (new XmlAtomicValue(SchemaType!, (string)value)); @@ -1957,11 +1884,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -2005,16 +1929,12 @@ private XmlUntypedConverter(XmlUntypedConverter atomicConverter, bool allowListT // ToBoolean //----------------------------------------------- - public override bool ToBoolean(string value) + public override bool ToBoolean(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToBoolean((string)value); } - public override bool ToBoolean(object value) + public override bool ToBoolean(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToBoolean((string)value); @@ -2027,16 +1947,12 @@ public override bool ToBoolean(object value) // ToDateTime //----------------------------------------------- - public override DateTime ToDateTime(string value) + public override DateTime ToDateTime(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return UntypedAtomicToDateTime((string)value); } - public override DateTime ToDateTime(object value) + public override DateTime ToDateTime(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTime((string)value); @@ -2048,17 +1964,13 @@ public override DateTime ToDateTime(object value) // ToDateTimeOffset //----------------------------------------------- - public override DateTimeOffset ToDateTimeOffset(string value) + public override DateTimeOffset ToDateTimeOffset(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return UntypedAtomicToDateTimeOffset((string)value); } - public override DateTimeOffset ToDateTimeOffset(object value) + public override DateTimeOffset ToDateTimeOffset(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return UntypedAtomicToDateTimeOffset((string)value); @@ -2070,16 +1982,12 @@ public override DateTimeOffset ToDateTimeOffset(object value) // ToDecimal //----------------------------------------------- - public override decimal ToDecimal(string value) + public override decimal ToDecimal(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToDecimal((string)value); } - public override decimal ToDecimal(object value) + public override decimal ToDecimal(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDecimal((string)value); @@ -2092,16 +2000,12 @@ public override decimal ToDecimal(object value) // ToDouble //----------------------------------------------- - public override double ToDouble(string value) + public override double ToDouble(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToDouble((string)value); } - public override double ToDouble(object value) + public override double ToDouble(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToDouble((string)value); @@ -2114,16 +2018,12 @@ public override double ToDouble(object value) // ToInt32 //----------------------------------------------- - public override int ToInt32(string value) + public override int ToInt32(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToInt32((string)value); } - public override int ToInt32(object value) + public override int ToInt32(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt32((string)value); @@ -2136,16 +2036,12 @@ public override int ToInt32(object value) // ToInt64 //----------------------------------------------- - public override long ToInt64(string value) + public override long ToInt64(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToInt64((string)value); } - public override long ToInt64(object value) + public override long ToInt64(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToInt64((string)value); @@ -2158,16 +2054,12 @@ public override long ToInt64(object value) // ToSingle //----------------------------------------------- - public override float ToSingle(string value) + public override float ToSingle(string value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - return XmlConvert.ToSingle((string)value); } - public override float ToSingle(object value) + public override float ToSingle(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == StringType) return XmlConvert.ToSingle((string)value); @@ -2212,10 +2104,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); @@ -2307,11 +2197,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - if (destinationType == ObjectType) destinationType = DefaultClrType!; if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == ByteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); @@ -2338,11 +2225,8 @@ public override object ChangeType(string value, Type destinationType, IXmlNamesp 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -2523,10 +2407,8 @@ private XmlAnyConverter(XmlTypeCode typeCode) : base(typeCode) // ToBoolean //----------------------------------------------- - public override bool ToBoolean(object value) + public override bool ToBoolean(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsBoolean; @@ -2539,10 +2421,8 @@ public override bool ToBoolean(object value) // ToDateTime //----------------------------------------------- - public override DateTime ToDateTime(object value) + public override DateTime ToDateTime(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDateTime; @@ -2554,10 +2434,8 @@ public override DateTime ToDateTime(object value) // ToDateTimeOffset //----------------------------------------------- - public override DateTimeOffset ToDateTimeOffset(object value) + public override DateTimeOffset ToDateTimeOffset(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return (DateTimeOffset)((XmlAtomicValue)value).ValueAs(DateTimeOffsetType); @@ -2570,10 +2448,8 @@ public override DateTimeOffset ToDateTimeOffset(object value) // ToDecimal //----------------------------------------------- - public override decimal ToDecimal(object value) + public override decimal ToDecimal(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((decimal)((XmlAtomicValue)value).ValueAs(DecimalType)); @@ -2586,10 +2462,8 @@ public override decimal ToDecimal(object value) // ToDouble //----------------------------------------------- - public override double ToDouble(object value) + public override double ToDouble(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsDouble; @@ -2602,10 +2476,8 @@ public override double ToDouble(object value) // ToInt32 //----------------------------------------------- - public override int ToInt32(object value) + public override int ToInt32(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsInt; @@ -2618,10 +2490,8 @@ public override int ToInt32(object value) // ToInt64 //----------------------------------------------- - public override long ToInt64(object value) + public override long ToInt64(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((XmlAtomicValue)value).ValueAsLong; @@ -2634,10 +2504,8 @@ public override long ToInt64(object value) // ToSingle //----------------------------------------------- - public override float ToSingle(object value) + public override float ToSingle(object value!!) { - if (value == null) throw new ArgumentNullException(nameof(value)); - Type sourceType = value.GetType(); if (sourceType == XmlAtomicValueType) return ((float)((XmlAtomicValue)value).ValueAs(SingleType)); @@ -2657,82 +2525,64 @@ public override float ToSingle(object value) // ChangeType //----------------------------------------------- - public override object ChangeType(bool value, Type destinationType) + public override object ChangeType(bool value, Type destinationType!!) { - if (destinationType == null) throw new ArgumentNullException(nameof(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!!) { - if (destinationType == null) throw new ArgumentNullException(nameof(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!!) { - if (destinationType == null) throw new ArgumentNullException(nameof(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!!) { - if (destinationType == null) throw new ArgumentNullException(nameof(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!!) { - if (destinationType == null) throw new ArgumentNullException(nameof(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!!) { - if (destinationType == null) throw new ArgumentNullException(nameof(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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - Type sourceType = value.GetType(); if (destinationType == ObjectType) destinationType = DefaultClrType!; @@ -2853,11 +2703,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(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) { @@ -2909,11 +2756,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); - return ChangeListType(value, destinationType, nsResolver); } @@ -3151,11 +2995,8 @@ 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) { - if (value == null) throw new ArgumentNullException(nameof(value)); - if (destinationType == null) throw new ArgumentNullException(nameof(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/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index 7b66766d4cab06..7475e00ad49c55 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,11 +189,8 @@ public XmlSerializer(Type type, XmlAttributeOverrides? overrides) : this(type, o } [RequiresUnreferencedCode(TrimSerializationWarning)] - public XmlSerializer(XmlTypeMapping xmlTypeMapping) + public XmlSerializer(XmlTypeMapping xmlTypeMapping!!) { - if (xmlTypeMapping == null) - throw new ArgumentNullException(nameof(xmlTypeMapping)); - if (Mode != SerializationMode.ReflectionOnly) { _tempAssembly = GenerateTempAssembly(xmlTypeMapping); @@ -309,13 +306,8 @@ private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? } [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) { - if (xmlMapping == null) - { - throw new ArgumentNullException(nameof(xmlMapping)); - } - xmlMapping.CheckShallow(); if (xmlMapping.IsSoap) { @@ -659,11 +651,8 @@ internal static bool GenerateSerializer(Type[]? types, XmlMapping[] mappings, St if (types == null || types.Length == 0) return false; - if (mappings == null) - throw new ArgumentNullException(nameof(mappings)); - - if (stream == null) - throw new ArgumentNullException(nameof(stream)); + ArgumentNullException.ThrowIfNull(mappings); + ArgumentNullException.ThrowIfNull(stream); if (XmlMapping.IsShallow(mappings)) { 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 996b35e8b7e69a..8fe6921dce1f0a 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,11 +27,8 @@ 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) { - if (name == null) throw new ArgumentNullException(nameof(name)); - if (namespaceURI == null) throw new ArgumentNullException(nameof(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 82b173a82adf6e..f7fb25d6ddb13a 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,11 +49,8 @@ internal XPathDocument() /// /// Create a new empty document. All names should be atomized using "nameTable". /// - internal XPathDocument(XmlNameTable nameTable) + internal XPathDocument(XmlNameTable nameTable!!) { - if (nameTable == null) - throw new ArgumentNullException(nameof(nameTable)); - _nameTable = nameTable; } @@ -67,11 +64,8 @@ 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) { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); - LoadFromReader(reader, space); } @@ -147,7 +141,7 @@ 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) { XPathDocumentBuilder builder; IXmlLineInfo? lineInfo; @@ -155,9 +149,6 @@ internal void LoadFromReader(XmlReader reader, XmlSpace space) bool topLevelReader; int initialDepth; - if (reader == null) - throw new ArgumentNullException(nameof(reader)); - // Determine line number provider lineInfo = reader as IXmlLineInfo; if (lineInfo == null || !lineInfo.HasLineInfo()) 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 965213102cf06d..0ae33dd9cafdda 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,12 +109,8 @@ public override object TypedValue } } - public virtual void SetTypedValue(object typedValue) + public virtual void SetTypedValue(object typedValue!!) { - if (typedValue == null) - { - throw new ArgumentNullException(nameof(typedValue)); - } switch (NodeType) { case XPathNodeType.Element: @@ -604,10 +600,8 @@ public virtual XmlReader ReadSubtree() return CreateReader(); } - public virtual void WriteSubtree(XmlWriter writer) + public virtual void WriteSubtree(XmlWriter writer!!) { - if (null == writer) - throw new ArgumentNullException(nameof(writer)); writer.WriteNode(this, true); } @@ -1341,12 +1335,8 @@ public virtual void ReplaceSelf(string newNode) ReplaceSelf(reader); } - public virtual void ReplaceSelf(XmlReader newNode) + public virtual void ReplaceSelf(XmlReader newNode!!) { - if (newNode == null) - { - throw new ArgumentNullException(nameof(newNode)); - } XPathNodeType type = NodeType; if (type == XPathNodeType.Root || type == XPathNodeType.Attribute @@ -1359,12 +1349,8 @@ public virtual void ReplaceSelf(XmlReader newNode) writer.Close(); } - public virtual void ReplaceSelf(XPathNavigator newNode) + public virtual void ReplaceSelf(XPathNavigator newNode!!) { - if (newNode == null) - { - throw new ArgumentNullException(nameof(newNode)); - } XmlReader reader = newNode.CreateReader(); ReplaceSelf(reader); } @@ -1501,23 +1487,15 @@ public virtual void AppendChild(string newChild) AppendChild(reader); } - public virtual void AppendChild(XmlReader newChild) + public virtual void AppendChild(XmlReader newChild!!) { - if (newChild == null) - { - throw new ArgumentNullException(nameof(newChild)); - } XmlWriter writer = AppendChild(); BuildSubtree(newChild, writer); writer.Close(); } - public virtual void AppendChild(XPathNavigator newChild) + public virtual void AppendChild(XPathNavigator newChild!!) { - if (newChild == null) - { - throw new ArgumentNullException(nameof(newChild)); - } if (!IsValidChildType(newChild.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -1532,23 +1510,15 @@ public virtual void PrependChild(string newChild) PrependChild(reader); } - public virtual void PrependChild(XmlReader newChild) + public virtual void PrependChild(XmlReader newChild!!) { - if (newChild == null) - { - throw new ArgumentNullException(nameof(newChild)); - } XmlWriter writer = PrependChild(); BuildSubtree(newChild, writer); writer.Close(); } - public virtual void PrependChild(XPathNavigator newChild) + public virtual void PrependChild(XPathNavigator newChild!!) { - if (newChild == null) - { - throw new ArgumentNullException(nameof(newChild)); - } if (!IsValidChildType(newChild.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -1563,23 +1533,15 @@ public virtual void InsertBefore(string newSibling) InsertBefore(reader); } - public virtual void InsertBefore(XmlReader newSibling) + public virtual void InsertBefore(XmlReader newSibling!!) { - if (newSibling == null) - { - throw new ArgumentNullException(nameof(newSibling)); - } XmlWriter writer = InsertBefore(); BuildSubtree(newSibling, writer); writer.Close(); } - public virtual void InsertBefore(XPathNavigator newSibling) + public virtual void InsertBefore(XPathNavigator newSibling!!) { - if (newSibling == null) - { - throw new ArgumentNullException(nameof(newSibling)); - } if (!IsValidSiblingType(newSibling.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -1594,23 +1556,15 @@ public virtual void InsertAfter(string newSibling) InsertAfter(reader); } - public virtual void InsertAfter(XmlReader newSibling) + public virtual void InsertAfter(XmlReader newSibling!!) { - if (newSibling == null) - { - throw new ArgumentNullException(nameof(newSibling)); - } XmlWriter writer = InsertAfter(); BuildSubtree(newSibling, writer); writer.Close(); } - public virtual void InsertAfter(XPathNavigator newSibling) + public virtual void InsertAfter(XPathNavigator newSibling!!) { - if (newSibling == null) - { - throw new ArgumentNullException(nameof(newSibling)); - } if (!IsValidSiblingType(newSibling.NodeType)) { throw new InvalidOperationException(SR.Xpn_BadPosition); @@ -2066,13 +2020,8 @@ private XmlReader CreateReader() return XPathNavigatorReader.Create(this); } - private XmlReader CreateContextReader(string xml, bool fromCurrentNode) + private XmlReader CreateContextReader(string xml!!, bool fromCurrentNode) { - if (xml == null) - { - throw new ArgumentNullException(nameof(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 703aca1d6e1e2d..cc155b51536a75 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,17 +20,13 @@ bool IEqualityComparer.Equals(object? obj1, object? obj2) return false; } - int IEqualityComparer.GetHashCode(object obj) + int IEqualityComparer.GetHashCode(object obj!!) { int hashCode; XPathNavigator? nav; XPathDocumentNavigator? xpdocNav; - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - else if (null != (xpdocNav = obj as XPathDocumentNavigator)) + if (null != (xpdocNav = obj as XPathDocumentNavigator)) { hashCode = xpdocNav.GetPositionHashCode(); } 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 d7edb4c9acbaee..152e317ca40757 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,10 +455,8 @@ public override int AttributeCount return null; } - public override string? GetAttribute(string localName, string? namespaceURI) + public override string? GetAttribute(string localName!!, string? namespaceURI) { - if (null == localName) - throw new ArgumentNullException(nameof(localName)); // reader allows calling GetAttribute, even when positioned inside attributes XPathNavigator nav = _nav; switch (nav.NodeType) @@ -554,10 +552,8 @@ public override string GetAttribute(int index) } - public override bool MoveToAttribute(string localName, string? namespaceName) + public override bool MoveToAttribute(string localName!!, string? namespaceName) { - if (null == localName) - throw new ArgumentNullException(nameof(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 ed42e646f8df24..ed1757d0b60d76 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -322,23 +322,13 @@ 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) { - if (s == null) - { - throw new ArgumentNullException(nameof(s)); - } - return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount); } - internal static string ToBinHexString(byte[] inArray) + internal static string ToBinHexString(byte[] inArray!!) { - if (inArray == null) - { - throw new ArgumentNullException(nameof(inArray)); - } - return BinHexEncoder.Encode(inArray, 0, inArray.Length); } @@ -348,13 +338,8 @@ internal static string ToBinHexString(byte[] inArray) /// /// /// - public static string VerifyName(string name) + public static string VerifyName(string name!!) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); @@ -414,13 +399,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); @@ -492,13 +472,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); @@ -542,25 +517,16 @@ 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!!) { - if (content == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (publicId == null) - { - throw new ArgumentNullException(nameof(publicId)); - } // returns the position of invalid character or -1 int pos = XmlCharType.IsPublicId(publicId); @@ -574,12 +540,8 @@ 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!!) { - if (content == null) - { - throw new ArgumentNullException(nameof(content)); - } // returns the position of invalid character or -1 int pos = XmlCharType.IsOnlyWhitespaceWithPos(content); @@ -829,13 +791,8 @@ 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!!) { - if (s == null) - { - throw new ArgumentNullException(nameof(s)); - } - if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); @@ -1288,32 +1245,20 @@ public static DateTime ToDateTime(string s, XmlDateTimeSerializationMode dateTim return dt; } - public static DateTimeOffset ToDateTimeOffset(string s) + public static DateTimeOffset ToDateTimeOffset(string s!!) { - if (s == null) - { - throw new ArgumentNullException(nameof(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) { - if (s == null) - { - throw new ArgumentNullException(nameof(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) { - if (s == null) - { - throw new ArgumentNullException(nameof(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 9e209bd16b61a9..bc3ced1aa9fc19 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs @@ -118,14 +118,8 @@ public virtual bool PopScope() return true; } - public virtual void AddNamespace(string prefix, string uri) + public virtual void AddNamespace(string prefix!!, string uri!!) { - if (uri == null) - throw new ArgumentNullException(nameof(uri)); - - if (prefix == null) - throw new ArgumentNullException(nameof(prefix)); - Debug.Assert(_nameTable != null); Debug.Assert(_nsdecls != null); prefix = _nameTable.Add(prefix); @@ -188,17 +182,8 @@ public virtual void AddNamespace(string prefix, string uri) } } - public virtual void RemoveNamespace(string prefix, string uri) + public virtual void RemoveNamespace(string prefix!!, string uri!!) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } - if (prefix == null) - { - throw new ArgumentNullException(nameof(prefix)); - } - Debug.Assert(_nsdecls != null); int declIndex = LookupNamespaceDecl(prefix); 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 1ae326c41bc12d..58eb5e550843b9 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,13 +35,8 @@ public CompilerErrorCollection() { } public int Add(CompilerError value) => List.Add(value); - public void AddRange(CompilerError[] value) + public void AddRange(CompilerError[] value!!) { - if (value == null) - { - throw new ArgumentNullException(nameof(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 8d1497f60aa46d..220693b894fc9b 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,16 +204,8 @@ internal bool MoveToNextNamespace() // // Constructor // - internal NavigatorInput(XPathNavigator navigator, string baseUri, InputScope? rootScope) + internal NavigatorInput(XPathNavigator navigator!!, string baseUri!!, InputScope? rootScope) { - if (navigator == null) - { - throw new ArgumentNullException(nameof(navigator)); - } - if (baseUri == null) - { - throw new ArgumentNullException(nameof(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 da293c56478dec..559a2a169f8f8f 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,24 +24,14 @@ public TextWriter Writer // Constructor // - internal TextOnlyOutput(Processor processor, Stream stream) + internal TextOnlyOutput(Processor processor, Stream stream!!) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - _processor = processor; _writer = new StreamWriter(stream, Output.Encoding); } - internal TextOnlyOutput(Processor processor, TextWriter writer) + internal TextOnlyOutput(Processor processor, TextWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 15360671a3ac94..e32732fe30c8e5 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,26 +13,16 @@ internal sealed class TextOutput : SequentialOutput { private TextWriter _writer; - internal TextOutput(Processor processor, Stream stream) + internal TextOutput(Processor processor, Stream stream!!) : base(processor) { - if (stream == null) - { - throw new ArgumentNullException(nameof(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) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 3e9d0054ec71dc..2db4ecb841b4bc 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,13 +11,8 @@ internal sealed class WriterOutput : IRecordOutput private XmlWriter _writer; private readonly Processor _processor; - internal WriterOutput(Processor processor, XmlWriter writer) + internal WriterOutput(Processor processor, XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 11ac3b1ce60501..1694851515ba8e 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,9 +123,8 @@ 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(); @@ -234,28 +233,24 @@ 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!!) { - CheckArguments(input, results); Transform(input, null, results, CreateDefaultResolver()); } - public void Transform(IXPathNavigable input, XsltArgumentList? arguments, XmlWriter results) + public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, XmlWriter results!!) { - CheckArguments(input, results); Transform(input, arguments, results, CreateDefaultResolver()); } - public void Transform(IXPathNavigable input, XsltArgumentList? arguments, TextWriter results) + public void Transform(IXPathNavigable input!!, XsltArgumentList? arguments, TextWriter results!!) { - CheckArguments(input, 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!!) { - CheckArguments(input, results); using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(input, arguments, writer, CreateDefaultResolver()); } @@ -264,28 +259,24 @@ public void Transform(IXPathNavigable input, XsltArgumentList? arguments, Stream // Transform methods which take an XmlReader //------------------------------------------------ - public void Transform(XmlReader input, XmlWriter results) + public void Transform(XmlReader input!!, XmlWriter results!!) { - CheckArguments(input, results); Transform(input, null, results, CreateDefaultResolver()); } - public void Transform(XmlReader input, XsltArgumentList? arguments, XmlWriter results) + public void Transform(XmlReader input!!, XsltArgumentList? arguments, XmlWriter results!!) { - CheckArguments(input, results); Transform(input, arguments, results, CreateDefaultResolver()); } - public void Transform(XmlReader input, XsltArgumentList? arguments, TextWriter results) + public void Transform(XmlReader input!!, XsltArgumentList? arguments, TextWriter results!!) { - CheckArguments(input, 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!!) { - CheckArguments(input, results); using XmlWriter writer = XmlWriter.Create(results, OutputSettings); Transform(input, arguments, writer, CreateDefaultResolver()); } @@ -297,40 +288,34 @@ public void Transform(XmlReader input, XsltArgumentList? arguments, Stream resul // suppress the message. //------------------------------------------------ - public void Transform(string inputUri, XmlWriter results) + public void Transform(string inputUri!!, XmlWriter results!!) { - CheckArguments(inputUri, 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!!) { - CheckArguments(inputUri, 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!!) { - CheckArguments(inputUri, 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!!) { - CheckArguments(inputUri, 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); @@ -343,34 +328,20 @@ 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) { - CheckArguments(input, 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) { - CheckArguments(input, results); CheckCommand(); _command.Execute(input.CreateNavigator()!, documentResolver, arguments, results); } - private static void CheckArguments(object input, object results) - { - ArgumentNullException.ThrowIfNull(input); - ArgumentNullException.ThrowIfNull(results); - } - - private static void CheckArguments(string inputUri, object results) - { - ArgumentNullException.ThrowIfNull(inputUri); - ArgumentNullException.ThrowIfNull(results); - } - [MemberNotNull(nameof(_command))] private void CheckCommand() { 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 28cda9fa635654..3088eba590a365 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,12 +51,8 @@ public void Load(XmlReader stylesheet) { Load(stylesheet, CreateDefaultResolver()); } - public void Load(XmlReader stylesheet, XmlResolver? resolver) + public void Load(XmlReader stylesheet!!, XmlResolver? resolver) { - if (stylesheet == null) - { - throw new ArgumentNullException(nameof(stylesheet)); - } Load(new XPathDocument(stylesheet, XmlSpace.Preserve), resolver); } @@ -64,30 +60,18 @@ public void Load(IXPathNavigable stylesheet) { Load(stylesheet, CreateDefaultResolver()); } - public void Load(IXPathNavigable stylesheet, XmlResolver? resolver) + public void Load(IXPathNavigable stylesheet!!, XmlResolver? resolver) { - if (stylesheet == null) - { - throw new ArgumentNullException(nameof(stylesheet)); - } Load(stylesheet.CreateNavigator()!, resolver); } - public void Load(XPathNavigator stylesheet) + public void Load(XPathNavigator stylesheet!!) { - if (stylesheet == null) - { - throw new ArgumentNullException(nameof(stylesheet)); - } Load(stylesheet, CreateDefaultResolver()); } - public void Load(XPathNavigator stylesheet, XmlResolver? resolver) + public void Load(XPathNavigator stylesheet!!, XmlResolver? resolver) { - if (stylesheet == null) - { - throw new ArgumentNullException(nameof(stylesheet)); - } Compile(stylesheet, resolver); } @@ -170,74 +154,42 @@ 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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } return Transform(input.CreateNavigator()!, args, resolver); } - public XmlReader Transform(IXPathNavigable input, XsltArgumentList? args) + public XmlReader Transform(IXPathNavigable input!!, XsltArgumentList? args) { - if (input == null) - { - throw new ArgumentNullException(nameof(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) { - if (input == null) - { - throw new ArgumentNullException(nameof(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) { - if (input == null) - { - throw new ArgumentNullException(nameof(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) { - if (input == null) - { - throw new ArgumentNullException(nameof(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) { - if (input == null) - { - throw new ArgumentNullException(nameof(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) { - if (input == null) - { - throw new ArgumentNullException(nameof(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) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } Transform(input.CreateNavigator()!, args, output, _DocumentResolver); } 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 e4ed81281a400d..8536e4beb1646e 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,29 +20,19 @@ public abstract partial class CustomReflectionContext : ReflectionContext protected CustomReflectionContext() : this(new IdentityReflectionContext()) { } - protected CustomReflectionContext(ReflectionContext source) + protected CustomReflectionContext(ReflectionContext source!!) { - SourceContext = source ?? 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 == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - return _projector.ProjectAssemblyIfNeeded(assembly); } - public override TypeInfo MapType(TypeInfo type) + public override TypeInfo MapType(TypeInfo type!!) { - if (type == 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 aac19da96e36da..dd2b782ac4855d 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,12 +8,12 @@ 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) { Debug.Assert(position >= -1); - ClassImpl = parameterType ?? throw new ArgumentNullException(nameof(parameterType)); - MemberImpl = member ?? throw new ArgumentNullException(nameof(member)); + ClassImpl = parameterType; + MemberImpl = member; NameImpl = name; PositionImpl = position; } 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 7f2526bbf20f7a..badbc3b6f045c1 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,11 +15,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (name.Length == 0) throw new ArgumentException("", nameof(name)); diff --git a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs index 6934766e36392e..0dd03017c9e4b3 100644 --- a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs +++ b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs @@ -249,7 +249,7 @@ public void GetRuntimeField() }); - AssertExtensions.Throws(null, () => + Assert.Throws(() => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeField(null); }); 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 cd56fe02ca60f8..c6b21b46212167 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 @@ -427,13 +427,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(suffix)); - } - // TODO: consider copying data from right to left while there is space if (!IsHead || !suffix.IsHead) @@ -678,13 +673,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (byteCount < 0) { throw new ArgumentOutOfRangeException(nameof(byteCount)); @@ -1026,13 +1016,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(value)); - } - WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); WriteUTF16(value); WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); 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 eb7ca38a6a7a18..ca4332bfd383a9 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,13 +26,8 @@ public BlobContentId(ImmutableArray id) { } - public unsafe BlobContentId(byte[] id) + public unsafe BlobContentId(byte[] id!!) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - if (id.Length != Size) { throw new ArgumentException(SR.Format(SR.UnexpectedArrayLength, Size), nameof(id)); @@ -53,15 +48,10 @@ public static BlobContentId FromHash(ImmutableArray hashCode) return FromHash(ImmutableByteArrayInterop.DangerousGetUnderlyingArray(hashCode)!); } - public static BlobContentId FromHash(byte[] hashCode) + public static BlobContentId FromHash(byte[] hashCode!!) { const int minHashSize = 20; - if (hashCode == null) - { - throw new ArgumentNullException(nameof(hashCode)); - } - if (hashCode.Length < minHashSize) { throw new ArgumentException(SR.Format(SR.HashTooShort, minHashSize), nameof(hashCode)); 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 5ae45500de8846..a6a4aac8a2cc9f 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 @@ -454,13 +454,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(value)); - } - WriteCompressedInteger(BlobUtilities.GetUserStringByteLength(value.Length)); WriteUTF16(value); WriteByte(BlobUtilities.GetUserStringTrailingByte(value)); 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 f675d4361dd5ef..1d2ff219a1bbb7 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 @@ -37,13 +37,8 @@ public static int GetTableRowCount(this MetadataReader reader, TableIndex tableI /// /// 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - return tableIndex switch { TableIndex.Module => reader.ModuleTable.RowSize, @@ -282,13 +277,8 @@ public static StringHandle GetNextHandle(this MetadataReader reader, StringHandl /// Enumerates entries of EnC log. /// /// is null. - public static IEnumerable GetEditAndContinueLogEntries(this MetadataReader reader) + public static IEnumerable GetEditAndContinueLogEntries(this MetadataReader reader!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++) { yield return new EditAndContinueLogEntry( @@ -301,13 +291,8 @@ 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!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++) { yield return new EntityHandle(reader.EncMapTable.GetToken(rid)); @@ -321,13 +306,8 @@ 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!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++) { yield return reader.PropertyMapTable.GetParentType(rid); @@ -341,13 +321,8 @@ 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!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++) { yield return reader.EventMapTable.GetParentType(rid); @@ -357,13 +332,8 @@ public static IEnumerable GetTypesWithEvents(this Metadata /// /// 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - var typeKind = (SignatureTypeKind)rawTypeKind; switch (typeKind) 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 6cdac1a324b58f..0679b389d61afa 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,11 +42,8 @@ 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 == null) - throw new ArgumentNullException(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 b5dc81c048d9bc..eb2e32d07cffe5 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,13 +68,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(start)); - } - if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); @@ -160,13 +155,8 @@ 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 == null) - { - throw new ArgumentNullException(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 3d97f85c9662f6..d5e3f7a6acb7d6 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,13 +41,8 @@ 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 == null) - { - throw new ArgumentNullException(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 8f769a21319a15..7f924ed70363c9 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,13 +21,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(peReader)); - } - var block = peReader.GetSectionData(relativeVirtualAddress); if (block.Length == 0) { @@ -76,13 +71,8 @@ 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 == null) - { - throw new ArgumentNullException(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/PEHeaders.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs index af4e9eb4dc7a31..b84652be123928 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,13 +70,8 @@ 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 == null) - { - throw new ArgumentNullException(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 0cee4c215cef15..46340375c745e7 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,13 +69,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(peImage)); - } - if (size < 0) { throw new ArgumentOutOfRangeException(nameof(size)); @@ -150,13 +145,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(peStream)); - } - if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); 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 4c0ec188cbfe01..c76a7cb88fdd8c 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs @@ -269,11 +269,8 @@ 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 == null) - throw new ArgumentNullException(nameof(match)); - MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; @@ -312,11 +309,8 @@ 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 == 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 cd766198a65208..897ce6890a6545 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,11 +103,8 @@ 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 == null) - throw new ArgumentNullException(nameof(resolver)); - this.resolver = resolver; if (coreAssemblyName != null) @@ -125,14 +122,10 @@ public MetadataLoadContext(MetadataAssemblyResolver resolver, string? coreAssemb /// 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 (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); - - if (assemblyPath == null) - throw new ArgumentNullException(nameof(assemblyPath)); - return LoadFromStreamCore(File.OpenRead(assemblyPath)); } @@ -141,14 +134,10 @@ 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 (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); - - if (assembly == null) - throw new ArgumentNullException(nameof(assembly)); - return LoadFromStreamCore(new MemoryStream(assembly)); } @@ -160,14 +149,10 @@ 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 (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); - - if (assembly == null) - throw new ArgumentNullException(nameof(assembly)); - assembly.Position = 0; return LoadFromStreamCore(assembly); } @@ -179,14 +164,10 @@ 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 (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); - - if (assemblyName == null) - throw new ArgumentNullException(nameof(assemblyName)); - AssemblyName assemblyNameObject = new AssemblyName(assemblyName); RoAssemblyName refName = assemblyNameObject.ToRoAssemblyName(); return ResolveAssembly(refName); @@ -199,14 +180,10 @@ 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 (IsDisposed) throw new ObjectDisposedException(nameof(MetadataLoadContext)); - - if (assemblyName == null) - throw new ArgumentNullException(nameof(assemblyName)); - RoAssemblyName refName = assemblyName.ToRoAssemblyName(); return ResolveAssembly(refName); } 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 acae80432247cf..65cbcba0372f63 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/PathAssemblyResolver.cs @@ -29,11 +29,8 @@ 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 == 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 9cfdf5b19d9354..c105c220588336 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,8 @@ 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 == null) - throw new ArgumentNullException(nameof(resourceName)); if (resourceName.Length == 0) throw new ArgumentException(nameof(resourceName)); @@ -59,10 +57,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(nameof(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 d141c710af2e84..34217ecdd6b24a 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,11 +59,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (!TryGetAssemblyFileInfo(name, includeManifestModule: true, out AssemblyFileInfo afi)) return null; 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 43609a2f3eb869..57fd648bbe12d2 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,11 +96,8 @@ 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 == 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/Methods/RoDefinitionMethod.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoDefinitionMethod.cs index d8cbb517045618..0d0f122a35bd5b 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,11 +100,8 @@ 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 == 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 8d1be59255ed71..bd6cef84f36262 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,10 +169,8 @@ 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 == 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 316d25a6086cf3..52919a1315581a 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,17 +9,13 @@ 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 == 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 == 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 94837cbfa2476c..e36ab027ab7fa9 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,11 +85,8 @@ 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 == 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 d7d3d8474d1da9..6f83b51797a64b 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,11 +8,8 @@ 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 == 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 f931cbe364b539..49e722736dd4a7 100644 --- a/src/libraries/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.cs +++ b/src/libraries/System.Reflection.TypeExtensions/src/System/Reflection/TypeExtensions.cs @@ -8,25 +8,22 @@ 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); } @@ -37,86 +34,75 @@ 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(); } @@ -127,19 +113,17 @@ 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); } @@ -150,138 +134,121 @@ 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); } } @@ -289,61 +256,52 @@ public static bool IsInstanceOfType(this Type type, [System.Diagnostics.CodeAnal 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); } } @@ -356,10 +314,8 @@ 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; @@ -378,10 +334,8 @@ 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) @@ -411,63 +365,54 @@ 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.Reflection/tests/AssemblyTests.cs b/src/libraries/System.Reflection/tests/AssemblyTests.cs index 1a85f648f83641..2ce8843eb3373d 100644 --- a/src/libraries/System.Reflection/tests/AssemblyTests.cs +++ b/src/libraries/System.Reflection/tests/AssemblyTests.cs @@ -693,10 +693,10 @@ public void AssemblyLoadFromString() public void AssemblyLoadFromStringNeg() { Assert.Throws(() => Assembly.Load((string)null)); - AssertExtensions.Throws(null, () => Assembly.Load(string.Empty)); + AssertExtensions.Throws("assemblyName", () => Assembly.Load(string.Empty)); string emptyCName = new string('\0', 1); - AssertExtensions.Throws(null, () => Assembly.Load(emptyCName)); + Assert.Throws(() => Assembly.Load(emptyCName)); Assert.Throws(() => Assembly.Load("no such assembly")); // No such assembly } 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 e251455cbfdac6..178ad1d94e0f97 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,15 +68,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); - // determine if the type is a primitive type if (s_primitiveTypes.TryGetValue(typeName, out Type? primitiveType)) { @@ -119,15 +112,8 @@ 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 == null) - throw new ArgumentNullException(nameof(name)); - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); - AddResourceData(name, typeName, new ResourceDataRecord(SerializationFormat.TypeConverterByteArray, value)); _requiresDeserializingResourceReader = true; @@ -140,12 +126,8 @@ public void AddTypeConverterResource(string name, byte[] value, string typeName) /// 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 == null) - throw new ArgumentNullException(nameof(name)); - if (value == null) - throw new ArgumentNullException(nameof(value)); if (typeName == null) { // Some resx-files are missing type information for binary-formatted resources. @@ -171,15 +153,8 @@ public void AddBinaryFormattedResource(string name, byte[] value, string? typeNa /// 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 == null) - throw new ArgumentNullException(nameof(name)); - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (typeName == 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 e0f5acbc8a5522..ce1758976ef665 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,14 +52,9 @@ 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 == null) - throw new ArgumentNullException(nameof(assemblyQualifiedTypeName1)); - if (assemblyQualifiedTypeName2 == 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 6d87f6a0964231..1bb99eb30ed9b5 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,26 +22,16 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(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!!) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (typeName == null) - throw new ArgumentNullException(nameof(typeName)); - if (serializedData == null) - throw new ArgumentNullException(nameof(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 803ca895074000..734cdea637908d 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,16 +24,8 @@ public ObjectCache Source get { return _source; } } - public CacheEntryRemovedArguments(ObjectCache source, CacheEntryRemovedReason reason, CacheItem cacheItem) + public CacheEntryRemovedArguments(ObjectCache source!!, CacheEntryRemovedReason reason, CacheItem cacheItem!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (cacheItem == 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 a7711b77266b98..d660879abdd5de 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,16 +46,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (key == 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 df6d6ea0a309d7..596a33e77942bb 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,13 +219,8 @@ 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 == 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 b49d9e138090e9..f89fede21f848e 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,13 +21,8 @@ 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) { - if (cacheName == null) - { - 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 750a0e037493b7..3bfa7ec6bda683 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,16 +93,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(filePath)); - } - if (onChangedCallback == null) - { - throw new ArgumentNullException(nameof(onChangedCallback)); - } FileInfo fileInfo = new FileInfo(filePath); string dir = Path.GetDirectoryName(filePath); DirectoryMonitor dirMon = _dirMonitors[dir] as DirectoryMonitor; @@ -143,16 +135,8 @@ void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCal fileSize = (fileInfo.Exists) ? fileInfo.Length : -1; } - void IFileChangeNotificationSystem.StopMonitoring(string filePath, object state) + void IFileChangeNotificationSystem.StopMonitoring(string filePath!!, object state!!) { - if (filePath == null) - { - throw new ArgumentNullException(nameof(filePath)); - } - if (state == 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 ecd228c35d5ba4..997477657ae022 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,12 +155,8 @@ 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 == 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 1a11c5f7cdc2ac..8515bbe795437f 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,12 +348,8 @@ private MemoryCache() Init(null); } - public MemoryCache(string name, NameValueCollection config = null) + public MemoryCache(string name!!, NameValueCollection config = null) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Empty_string_invalid, nameof(name)); @@ -368,12 +364,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(name)); - } if (name.Length == 0) { throw new ArgumentException(SR.Empty_string_invalid, nameof(name)); @@ -399,12 +391,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(key)); - } DateTimeOffset absExp = ObjectCache.InfiniteAbsoluteExpiration; TimeSpan slidingExp = ObjectCache.NoSlidingExpiration; CacheItemPriority priority = CacheItemPriority.Default; @@ -632,12 +620,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(item)); - } return new CacheItem(item.Key, AddOrGetExistingInternal(item.Key, item.Value, policy)); } @@ -672,12 +656,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(item)); - } Set(item.Key, item.Value, policy); } @@ -732,17 +712,13 @@ 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 == null) - { - throw new ArgumentNullException(nameof(key)); - } if (changeMonitors == null && absoluteExpiration == ObjectCache.InfiniteAbsoluteExpiration && slidingExpiration == ObjectCache.NoSlidingExpiration) @@ -897,12 +873,8 @@ 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 == 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 792a2da188348c..eb027e99ec7fc8 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,10 +112,6 @@ internal MemoryCacheEntry(string key, CacheEntryRemovedCallback removedCallback, MemoryCache cache) : base(key) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } _utcCreated = DateTime.UtcNow; _value = value; diff --git a/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs index 4d1353ffd6546b..2221e887354eee 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs @@ -194,15 +194,15 @@ public void OffsetOf_NullType_ThrowsArgumentNullException() [Fact] public void OffsetOf_NullFieldName_ThrowsArgumentNullException() { - AssertExtensions.Throws(null, () => Marshal.OffsetOf(new object().GetType(), null)); - AssertExtensions.Throws(null, () => Marshal.OffsetOf(null)); + Assert.Throws(() => Marshal.OffsetOf(new object().GetType(), null)); + Assert.Throws(() => Marshal.OffsetOf(null)); } [Fact] public void OffsetOf_NoSuchFieldName_ThrowsArgumentException() { - AssertExtensions.Throws("fieldName", () => Marshal.OffsetOf(typeof(NonExistField), "NonExistField")); - AssertExtensions.Throws("fieldName", () => Marshal.OffsetOf("NonExistField")); + Assert.Throws(() => Marshal.OffsetOf(typeof(NonExistField), "NonExistField")); + Assert.Throws(() => Marshal.OffsetOf("NonExistField")); } [Fact] 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 984bde00e7cb27..d9ae36628b47eb 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs @@ -360,13 +360,8 @@ 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) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - return ParseBigInteger(value.AsSpan(), style, info); } 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 b3f94a260d7c53..37526aa85f5a58 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 @@ -168,14 +168,9 @@ public static MemberInfo[] GetSerializableMembers( } public static MemberInfo[] GetSerializableMembers( - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type!!, StreamingContext context) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - // If we've already gathered the members for this type, just return them. // Otherwise, get them and add them. return s_memberInfoTable.GetOrAdd( @@ -214,20 +209,8 @@ 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!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - if (members == null) - { - throw new ArgumentNullException(nameof(members)); - } - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } if (members.Length != data.Length) { throw new ArgumentException(SR.Argument_DataLengthDifferent); @@ -264,17 +247,8 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj return obj; } - public static object?[] GetObjectData(object obj, MemberInfo[] members) + public static object?[] GetObjectData(object obj!!, MemberInfo[] members!!) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - if (members == null) - { - throw new ArgumentNullException(nameof(members)); - } - object?[] data = new object[members.Length]; for (int i = 0; i < members.Length; i++) { @@ -295,22 +269,14 @@ public static object PopulateObjectMembers(object obj, MemberInfo[] members, obj return data; } - public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) + public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate!!) { - if (innerSurrogate == null) - { - throw new ArgumentNullException(nameof(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) { - if (assem == null) - { - throw new ArgumentNullException(nameof(assem)); - } return assem.GetType(name, throwOnError: false, ignoreCase: false); } @@ -329,13 +295,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(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/BinaryFormatter.Core.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs index 8d3e437a0b5c5c..5021aaa157c942 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs @@ -18,10 +18,8 @@ public object Deserialize(Stream serializationStream) throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } - if (serializationStream == null) - { - throw new ArgumentNullException(nameof(serializationStream)); - } + ArgumentNullException.ThrowIfNull(serializationStream); + if (serializationStream.CanSeek && (serializationStream.Length == 0)) { throw new SerializationException(SR.Serialization_Stream); @@ -69,10 +67,7 @@ public void Serialize(Stream serializationStream, object graph) throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } - if (serializationStream == null) - { - throw new ArgumentNullException(nameof(serializationStream)); - } + ArgumentNullException.ThrowIfNull(serializationStream); var formatterEnums = new InternalFE() { 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 de852ca9400075..c5986bc8edb399 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,13 +63,8 @@ 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) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } - _stream = stream; _surrogates = selector; _context = context; @@ -78,13 +73,8 @@ internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingCont } [RequiresUnreferencedCode("Types might be removed")] - internal object Deserialize(BinaryParser serParser) + internal object Deserialize(BinaryParser serParser!!) { - if (serParser == null) - { - throw new ArgumentNullException(nameof(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 26a6a41c7c7e92..b7c3e57ac6d6df 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,17 +50,8 @@ internal ObjectWriter(ISurrogateSelector? selector, StreamingContext context, In } [RequiresUnreferencedCode(ObjectWriterUnreferencedCodeMessage)] - internal void Serialize(object graph, BinaryFormatterWriter serWriter) + internal void Serialize(object graph!!, BinaryFormatterWriter serWriter!!) { - if (graph == null) - { - throw new ArgumentNullException(nameof(graph)); - } - if (serWriter == null) - { - throw new ArgumentNullException(nameof(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 704cbe4aafcc85..c19f422bf33e14 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,13 +61,8 @@ 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) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } - bool found; int pos = FindElement(obj, out found); @@ -96,13 +91,8 @@ 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) { - if (obj == null) - { - throw new ArgumentNullException(nameof(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 a3b058fc00bd9e..6a3ef39fb0deb8 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,12 +658,8 @@ 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) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } if (objectID <= 0) { throw new ArgumentOutOfRangeException(nameof(objectID), SR.ArgumentOutOfRange_ObjectID); @@ -771,12 +767,8 @@ public void RegisterObject(object obj, long objectID, SerializationInfo? info, l /// 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) { - if (obj == null) - { - throw new ArgumentNullException(nameof(obj)); - } if (!(obj is ISerializable)) { throw new ArgumentException(SR.Serialization_NotISer); @@ -931,10 +923,7 @@ public virtual void RecordFixup(long objectToBeFixed, MemberInfo member, long ob { throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } - if (member == null) - { - throw new ArgumentNullException(nameof(member)); - } + ArgumentNullException.ThrowIfNull(member); if (!(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib { throw new SerializationException(SR.Format(SR.Serialization_InvalidType, member.GetType())); @@ -952,10 +941,7 @@ public virtual void RecordDelayedFixup(long objectToBeFixed, string memberName, { throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } - if (memberName == null) - { - throw new ArgumentNullException(nameof(memberName)); - } + ArgumentNullException.ThrowIfNull(memberName); //Create a new fixup holder FixupHolder fixup = new FixupHolder(objectRequired, memberName, FixupHolder.DelayedFixup); @@ -976,10 +962,7 @@ public virtual void RecordArrayElementFixup(long arrayToBeFixed, int[] indices, { throw new ArgumentOutOfRangeException(arrayToBeFixed <= 0 ? nameof(arrayToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall); } - if (indices == null) - { - throw new ArgumentNullException(nameof(indices)); - } + ArgumentNullException.ThrowIfNull(indices); FixupHolder fixup = new FixupHolder(objectRequired, indices, FixupHolder.ArrayFixup); RegisterFixup(fixup, arrayToBeFixed, objectRequired); 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 39bb23890fdee1..17703be74d3b29 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,17 +11,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - if (surrogate == null) - { - throw new ArgumentNullException(nameof(surrogate)); - } - var key = new SurrogateKey(type, context); _surrogates.Add(key, surrogate); // Hashtable does duplicate checking. } @@ -56,13 +47,8 @@ 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!!) { - if (selector == null) - { - throw new ArgumentNullException(nameof(selector)); - } - // Verify that we don't try and add ourself twice. if (selector == this) { @@ -150,13 +136,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - selector = this; SurrogateKey key = new SurrogateKey(type, context); @@ -174,13 +155,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(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 2dafddc3128e5d..781c63202b4c28 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,15 +108,11 @@ 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) { int Length = BinaryLength; // Invokes the most derived property - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - else if (offset < 0) + if (offset < 0) { throw new ArgumentOutOfRangeException( nameof(offset), @@ -241,13 +237,9 @@ 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) { - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - else if (offset < 0) + if (offset < 0) { throw new ArgumentOutOfRangeException( nameof(offset), @@ -660,14 +652,9 @@ 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) { - if (securityIdentifier == null) - { - throw new ArgumentNullException(nameof(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 d6c4a5175f9805..dabcef119438fa 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,13 +37,8 @@ public sealed class AceEnumerator : IEnumerator #region Constructors - internal AceEnumerator(GenericAcl collection) + internal AceEnumerator(GenericAcl collection!!) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } - _acl = collection; Reset(); } @@ -167,13 +162,8 @@ protected GenericAcl() #region ICollection Implementation - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (array.Rank != 1) { throw new RankException(SR.Rank_MultiDimNotSupported); @@ -240,13 +230,8 @@ 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) { - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - if (offset < 0) { // @@ -286,13 +271,9 @@ private static void VerifyHeader(byte[] binaryForm, int offset, out byte revisio throw new ArgumentOutOfRangeException(nameof(binaryForm), SR.ArgumentOutOfRange_ArrayTooSmall); } - private void MarshalHeader(byte[] binaryForm, int offset) + private void MarshalHeader(byte[] binaryForm!!, int offset) { - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - else if (offset < 0) + if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } @@ -566,13 +547,8 @@ 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!!) { - if (ace == null) - { - throw new ArgumentNullException(nameof(ace)); - } - if (BinaryLength + ace.BinaryLength > MaxBinaryLength) { throw new OverflowException(SR.AccessControl_AclTooLong); @@ -1857,14 +1833,9 @@ 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() { - if (rawAcl == null) - { - throw new ArgumentNullException(nameof(rawAcl)); - } - _isContainer = isContainer; _isDS = isDS; @@ -1985,13 +1956,8 @@ 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) { - if (sid == null) - { - throw new ArgumentNullException(nameof(sid)); - } - ThrowIfNotCanonical(); bool aceMerged = false; // if still false after all attempts to merge, create new entry @@ -2068,13 +2034,8 @@ internal void AddQualifiedAce(SecurityIdentifier sid, AceQualifier qualifier, in // 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) { - if (sid == null) - { - throw new ArgumentNullException(nameof(sid)); - } - if (qualifier == AceQualifier.SystemAudit && ((flags & AceFlags.AuditFlags) == 0)) { @@ -2856,13 +2817,8 @@ public void RemoveInheritedAces() OnAclModificationTried(); } - public void Purge(SecurityIdentifier sid) + public void Purge(SecurityIdentifier sid!!) { - if (sid == null) - { - throw new ArgumentNullException(nameof(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 81fa5c2dab9980..1c60bdc45dbe2b 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,13 +222,8 @@ private bool AceNeedsTranslation([NotNullWhen(true)] CommonAce? ace, bool isAcce // // 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) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try { @@ -352,13 +347,8 @@ 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) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try { @@ -435,13 +425,8 @@ protected override bool ModifyAudit(AccessControlModification modification, Audi #region Public Methods - protected void AddAccessRule(AccessRule rule) + protected void AddAccessRule(AccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -454,13 +439,8 @@ protected void AddAccessRule(AccessRule rule) } } - protected void SetAccessRule(AccessRule rule) + protected void SetAccessRule(AccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -473,13 +453,8 @@ protected void SetAccessRule(AccessRule rule) } } - protected void ResetAccessRule(AccessRule rule) + protected void ResetAccessRule(AccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -494,13 +469,8 @@ protected void ResetAccessRule(AccessRule rule) return; } - protected bool RemoveAccessRule(AccessRule rule) + protected bool RemoveAccessRule(AccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -518,13 +488,8 @@ protected bool RemoveAccessRule(AccessRule rule) } } - protected void RemoveAccessRuleAll(AccessRule rule) + protected void RemoveAccessRuleAll(AccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -544,13 +509,8 @@ protected void RemoveAccessRuleAll(AccessRule rule) return; } - protected void RemoveAccessRuleSpecific(AccessRule rule) + protected void RemoveAccessRuleSpecific(AccessRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -568,13 +528,8 @@ protected void RemoveAccessRuleSpecific(AccessRule rule) } } - protected void AddAuditRule(AuditRule rule) + protected void AddAuditRule(AuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -587,13 +542,8 @@ protected void AddAuditRule(AuditRule rule) } } - protected void SetAuditRule(AuditRule rule) + protected void SetAuditRule(AuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -606,13 +556,8 @@ protected void SetAuditRule(AuditRule rule) } } - protected bool RemoveAuditRule(AuditRule rule) + protected bool RemoveAuditRule(AuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -625,13 +570,8 @@ protected bool RemoveAuditRule(AuditRule rule) } } - protected void RemoveAuditRuleAll(AuditRule rule) + protected void RemoveAuditRuleAll(AuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - WriteLock(); try @@ -644,13 +584,8 @@ protected void RemoveAuditRuleAll(AuditRule rule) } } - protected void RemoveAuditRuleSpecific(AuditRule rule) + protected void RemoveAuditRuleSpecific(AuditRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(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 6a50a775a1ea41..d375fde326d44d 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,13 +343,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - Persist(name, null, includeSections, exceptionContext); } @@ -364,13 +359,8 @@ 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) { - if (handle == null) - { - throw new ArgumentNullException(nameof(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 b07608cc5e05ef..2edf3e0cc7dd85 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,14 +71,9 @@ 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() { - if (securityDescriptor == null) - { - throw new ArgumentNullException(nameof(securityDescriptor)); - } - _securityDescriptor = securityDescriptor; } @@ -361,13 +356,8 @@ protected virtual void Persist(SafeHandle handle, AccessControlSections includeS } } - public void SetOwner(IdentityReference identity) + public void SetOwner(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - WriteLock(); try @@ -404,13 +394,8 @@ public void SetOwner(IdentityReference identity) } } - public void SetGroup(IdentityReference identity) + public void SetGroup(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - WriteLock(); try @@ -424,13 +409,8 @@ public void SetGroup(IdentityReference identity) } } - public virtual void PurgeAccessRules(IdentityReference identity) + public virtual void PurgeAccessRules(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - WriteLock(); try @@ -444,12 +424,8 @@ public virtual void PurgeAccessRules(IdentityReference identity) } } - public virtual void PurgeAuditRules(IdentityReference identity) + public virtual void PurgeAuditRules(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } WriteLock(); @@ -586,13 +562,8 @@ public void SetSecurityDescriptorSddlForm(string sddlForm) SetSecurityDescriptorSddlForm(sddlForm, AccessControlSections.All); } - public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections) + public void SetSecurityDescriptorSddlForm(string sddlForm!!, AccessControlSections includeSections) { - if (sddlForm == null) - { - throw new ArgumentNullException(nameof(sddlForm)); - } - if ((includeSections & AccessControlSections.All) == 0) { throw new ArgumentException( @@ -635,13 +606,8 @@ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm) SetSecurityDescriptorBinaryForm(binaryForm, AccessControlSections.All); } - public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections) + public void SetSecurityDescriptorBinaryForm(byte[] binaryForm!!, AccessControlSections includeSections) { - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - if ((includeSections & AccessControlSections.All) == 0) { throw new ArgumentException( @@ -668,13 +634,8 @@ public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSect 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) { - if (rule == null) - { - throw new ArgumentNullException(nameof(rule)); - } - if (!this.AccessRuleType.IsAssignableFrom(rule.GetType())) { throw new ArgumentException( @@ -694,13 +655,8 @@ 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) { - if (rule == null) - { - throw new ArgumentNullException(nameof(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 49c2d23a33ff1f..c184a1ac9e15bc 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,13 +361,8 @@ public bool IsImpersonating #region Constructors - public Privilege(string privilegeName) + public Privilege(string privilegeName!!) { - if (privilegeName == null) - { - throw new ArgumentNullException(nameof(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 201acabc7a52ca..3121312f613f15 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,17 +31,12 @@ public abstract class AuthorizationRule #region Constructors protected internal AuthorizationRule( - IdentityReference identity, + IdentityReference identity!!, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { - if (identity == null) - { - throw new ArgumentNullException(nameof(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 6c4a290db11dfe..8ce2a85e103ad7 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,13 +257,8 @@ 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) { - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), @@ -466,18 +461,13 @@ 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() { // // The array passed in must be valid // - if (binaryForm == null) - { - throw new ArgumentNullException(nameof(binaryForm)); - } - if (offset < 0) { // @@ -621,13 +611,8 @@ public RawSecurityDescriptor(byte[] binaryForm, int offset) #region Static Methods - private static byte[] BinaryFormFromSddlForm(string sddlForm) + private static byte[] BinaryFormFromSddlForm(string sddlForm!!) { - if (sddlForm == null) - { - throw new ArgumentNullException(nameof(sddlForm)); - } - int error; IntPtr byteArray = IntPtr.Zero; uint byteArraySize = 0; @@ -939,13 +924,8 @@ 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) { - if (rawSecurityDescriptor == null) - { - throw new ArgumentNullException(nameof(rawSecurityDescriptor)); - } - CreateFromParts( isContainer, isDS, @@ -1199,26 +1179,16 @@ public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInherit } } - public void PurgeAccessControl(SecurityIdentifier sid) + public void PurgeAccessControl(SecurityIdentifier sid!!) { - if (sid == null) - { - throw new ArgumentNullException(nameof(sid)); - } - if (DiscretionaryAcl != null) { DiscretionaryAcl.Purge(sid); } } - public void PurgeAudit(SecurityIdentifier sid) + public void PurgeAudit(SecurityIdentifier sid!!) { - if (sid == null) - { - throw new ArgumentNullException(nameof(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 fbb764fb0d00f0..8e7e191416d0f7 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,13 +56,8 @@ 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) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - _subject = subject; SerializationMask mask = (SerializationMask)reader.ReadInt32(); @@ -251,18 +246,8 @@ 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) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - _type = type; _value = value; _valueType = string.IsNullOrEmpty(valueType) ? ClaimValueTypes.String : valueType; @@ -295,11 +280,8 @@ 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) { - if (other == null) - throw new ArgumentNullException(nameof(other)); - _issuer = other._issuer; _originalIssuer = other._originalIssuer; _subject = subject; @@ -432,13 +414,8 @@ 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) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 6da13d9a9bf80c..fa49abae75cb4f 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,11 +195,8 @@ public ClaimsIdentity(IIdentity? identity, IEnumerable? claims, string? a /// /// a pointing to a . /// if 'reader' is null. - public ClaimsIdentity(BinaryReader reader) + public ClaimsIdentity(BinaryReader reader!!) { - if (reader == null) - throw new ArgumentNullException(nameof(reader)); - Initialize(reader); } @@ -208,13 +205,8 @@ public ClaimsIdentity(BinaryReader reader) /// /// to copy. /// if 'other' is null. - protected ClaimsIdentity(ClaimsIdentity other) + protected ClaimsIdentity(ClaimsIdentity other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - if (other._actor != null) { _actor = other._actor.Clone(); @@ -417,13 +409,8 @@ 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!!) { - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } - if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); @@ -440,13 +427,8 @@ 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!!) { - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } - foreach (Claim? claim in claims) { if (claim == null) @@ -557,13 +539,8 @@ 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!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - foreach (Claim claim in Claims) { if (match(claim)) @@ -580,13 +557,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - foreach (Claim claim in Claims) { if (claim != null) @@ -605,13 +577,8 @@ 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!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - foreach (Claim claim in Claims) { if (match(claim)) @@ -630,13 +597,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - foreach (Claim claim in Claims) { if (claim != null) @@ -657,13 +619,8 @@ 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!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - foreach (Claim claim in Claims) { if (match(claim)) @@ -684,18 +641,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - foreach (Claim claim in Claims) { if (claim != null @@ -715,13 +662,8 @@ 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!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 0; int numPropertiesToRead = reader.ReadInt32(); @@ -798,13 +740,8 @@ 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!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - return new Claim(reader, this); } @@ -824,13 +761,8 @@ 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) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 4e99666d326175..59d4b794abf131 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,13 +52,8 @@ 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!!) { - if (identities == null) - { - throw new ArgumentNullException(nameof(identities)); - } - foreach (ClaimsIdentity identity in identities) { if (identity != null) @@ -106,13 +101,8 @@ public ClaimsPrincipal() /// /// the subjects in the principal. /// if 'identities' is null. - public ClaimsPrincipal(IEnumerable identities) + public ClaimsPrincipal(IEnumerable identities!!) { - if (identities == null) - { - throw new ArgumentNullException(nameof(identities)); - } - _identities.AddRange(identities); } @@ -121,13 +111,8 @@ public ClaimsPrincipal(IEnumerable identities) /// /// representing the subject in the principal. /// if 'identity' is null. - public ClaimsPrincipal(IIdentity identity) + public ClaimsPrincipal(IIdentity identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - if (identity is ClaimsIdentity ci) { _identities.Add(ci); @@ -143,13 +128,8 @@ public ClaimsPrincipal(IIdentity identity) /// /// used to form this instance. /// if 'principal' is null. - public ClaimsPrincipal(IPrincipal principal) + public ClaimsPrincipal(IPrincipal principal!!) { - if (null == principal) - { - throw new ArgumentNullException(nameof(principal)); - } - // // If IPrincipal is a ClaimsPrincipal add all of the identities // If IPrincipal is not a ClaimsPrincipal, create a new identity from IPrincipal.Identity @@ -174,13 +154,8 @@ public ClaimsPrincipal(IPrincipal principal) /// /// a pointing to a . /// if 'reader' is null. - public ClaimsPrincipal(BinaryReader reader) + public ClaimsPrincipal(BinaryReader reader!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesToRead = reader.ReadInt32(); int numPropertiesRead = 0; @@ -213,13 +188,8 @@ public ClaimsPrincipal(BinaryReader reader) /// /// the add. /// if 'identity' is null. - public virtual void AddIdentity(ClaimsIdentity identity) + public virtual void AddIdentity(ClaimsIdentity identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - _identities.Add(identity); } @@ -228,13 +198,8 @@ 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!!) { - if (identities == null) - { - throw new ArgumentNullException(nameof(identities)); - } - _identities.AddRange(identities); } @@ -280,13 +245,8 @@ 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!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - return new ClaimsIdentity(reader); } @@ -309,13 +269,8 @@ 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!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - foreach (ClaimsIdentity identity in Identities) { if (identity != null) @@ -335,13 +290,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - foreach (ClaimsIdentity identity in Identities) { if (identity != null) @@ -361,13 +311,8 @@ 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!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - Claim? claim = null; foreach (ClaimsIdentity identity in Identities) @@ -392,13 +337,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - Claim? claim = null; for (int i = 0; i < _identities.Count; i++) @@ -423,13 +363,8 @@ 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!!) { - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } - for (int i = 0; i < _identities.Count; i++) { if (_identities[i] != null) @@ -453,18 +388,8 @@ 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!!) { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - for (int i = 0; i < _identities.Count; i++) { if (_identities[i] != null) @@ -546,13 +471,8 @@ 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) { - if (writer == null) - { - throw new ArgumentNullException(nameof(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 bb222ee9c77af3..13e034120e47b3 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,24 +11,16 @@ public class GenericIdentity : ClaimsIdentity private readonly string m_name; private readonly string m_type; - public GenericIdentity(string name) + public GenericIdentity(string name!!) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - m_name = name; m_type = ""; AddNameClaim(); } - public GenericIdentity(string name, string type) + public GenericIdentity(string name!!, string type!!) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - if (type == null) - throw new ArgumentNullException(nameof(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 ed11066aed5de9..1cfeabf5a5677a 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,11 +12,8 @@ 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) { - if (identity == null) - throw new ArgumentNullException(nameof(identity)); - m_identity = identity; if (roles != null) { 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 7386c67b655fa0..3d70d4f8092272 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,19 +23,13 @@ public CryptographicAttributeObjectCollection(CryptographicAttributeObject attri _list.Add(attribute); } - public int Add(AsnEncodedData asnEncodedData) + public int Add(AsnEncodedData asnEncodedData!!) { - if (asnEncodedData == 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 == null) - throw new ArgumentNullException(nameof(attribute)); - // // Merge with existing attribute, if already existed, else add as new. // @@ -77,11 +71,8 @@ internal void AddWithoutMerge(CryptographicAttributeObject attribute) _list.Add(attribute); } - public void Remove(CryptographicAttributeObject attribute) + public void Remove(CryptographicAttributeObject attribute!!) { - if (attribute == null) - throw new ArgumentNullException(nameof(attribute)); - _list.Remove(attribute); } @@ -127,10 +118,8 @@ IEnumerator IEnumerable.GetEnumerator() return new CryptographicAttributeObjectEnumerator(this); } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -145,10 +134,8 @@ void ICollection.CopyTo(Array array, int index) } } - public void CopyTo(CryptographicAttributeObject[] array, int index) + public void CopyTo(CryptographicAttributeObject[] array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); 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 3c4188f44c03e7..9fa5dcc89fabe4 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,11 +19,11 @@ public CmsRecipient(X509Certificate2 certificate) #else public #endif - CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding) + CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding!!) : this(certificate) { ValidateRSACertificate(certificate); - RSAEncryptionPadding = rsaEncryptionPadding ?? throw new ArgumentNullException(nameof(rsaEncryptionPadding)); + RSAEncryptionPadding = rsaEncryptionPadding; } #if NETSTANDARD2_0 @@ -31,18 +31,15 @@ public CmsRecipient(X509Certificate2 certificate) #else public #endif - CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding) + CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding!!) : this(recipientIdentifierType, certificate) { ValidateRSACertificate(certificate); - RSAEncryptionPadding = rsaEncryptionPadding ?? throw new ArgumentNullException(nameof(rsaEncryptionPadding)); + RSAEncryptionPadding = rsaEncryptionPadding; } - public CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate) + public CmsRecipient(SubjectIdentifierType recipientIdentifierType, X509Certificate2 certificate!!) { - if (certificate == 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 9a040572e4884c..0e65973e311b2c 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,21 +53,15 @@ public int Count } } - public int Add(CmsRecipient recipient) + public int Add(CmsRecipient recipient!!) { - if (recipient == 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 == null) - throw new ArgumentNullException(nameof(recipient)); - _recipients.Remove(recipient); } @@ -81,10 +75,8 @@ IEnumerator IEnumerable.GetEnumerator() return new CmsRecipientEnumerator(this); } - public void CopyTo(Array array, int index) + public void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -99,10 +91,8 @@ public void CopyTo(Array array, int index) } } - public void CopyTo(CmsRecipient[] array, int index) + public void CopyTo(CmsRecipient[] array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); 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 cb5d774908f2c4..cdc8659b487f62 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,13 +19,8 @@ public ContentInfo(byte[] content) { } - public ContentInfo(Oid contentType, byte[] content) + public ContentInfo(Oid contentType!!, byte[] content!!) { - if (contentType == null) - throw new ArgumentNullException(nameof(contentType)); - if (content == null) - throw new ArgumentNullException(nameof(content)); - ContentType = contentType; Content = content; } @@ -34,10 +29,8 @@ public ContentInfo(Oid contentType, byte[] content) public byte[] Content { get; } - public static Oid GetContentType(byte[] encodedMessage) + public static Oid GetContentType(byte[] encodedMessage!!) { - if (encodedMessage == 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 eb99ba364cfeb1..f33f8c2b36a8e0 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,13 +25,8 @@ public EnvelopedCms(ContentInfo contentInfo) { } - public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) + public EnvelopedCms(ContentInfo contentInfo!!, AlgorithmIdentifier encryptionAlgorithm!!) { - if (contentInfo == null) - throw new ArgumentNullException(nameof(contentInfo)); - if (encryptionAlgorithm == 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; @@ -84,19 +79,13 @@ 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 == null) - throw new ArgumentNullException(nameof(recipient)); - Encrypt(new CmsRecipientCollection(recipient)); } - public void Encrypt(CmsRecipientCollection recipients) + public void Encrypt(CmsRecipientCollection recipients!!) { - if (recipients == 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); @@ -124,11 +113,8 @@ 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 == null) - throw new ArgumentNullException(nameof(encodedMessage)); - Decode(new ReadOnlySpan(encodedMessage)); } @@ -175,38 +161,23 @@ public void Decrypt() DecryptContent(RecipientInfos, null); } - public void Decrypt(RecipientInfo recipientInfo) + public void Decrypt(RecipientInfo recipientInfo!!) { - if (recipientInfo == 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 == null) - throw new ArgumentNullException(nameof(recipientInfo)); - - if (extraStore == null) - throw new ArgumentNullException(nameof(extraStore)); - DecryptContent(new RecipientInfoCollection(recipientInfo), extraStore); } - public void Decrypt(X509Certificate2Collection extraStore) + public void Decrypt(X509Certificate2Collection extraStore!!) { - if (extraStore == 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 == 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 e7c4e8c4deb85f..1f3c77bb93ba6a 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,14 +30,10 @@ public void AddSafeContentsEncrypted( } public void AddSafeContentsEncrypted( - Pkcs12SafeContents safeContents, + Pkcs12SafeContents safeContents!!, ReadOnlySpan passwordBytes, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (safeContents == null) - throw new ArgumentNullException(nameof(safeContents)); - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) @@ -78,14 +74,10 @@ public void AddSafeContentsEncrypted( } public void AddSafeContentsEncrypted( - Pkcs12SafeContents safeContents, + Pkcs12SafeContents safeContents!!, ReadOnlySpan password, - PbeParameters pbeParameters) + PbeParameters pbeParameters!!) { - if (safeContents == null) - throw new ArgumentNullException(nameof(safeContents)); - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); if (pbeParameters.IterationCount < 1) throw new ArgumentOutOfRangeException(nameof(pbeParameters)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) @@ -113,10 +105,8 @@ public void AddSafeContentsEncrypted( }); } - public void AddSafeContentsUnencrypted(Pkcs12SafeContents safeContents) + public void AddSafeContentsUnencrypted(Pkcs12SafeContents safeContents!!) { - if (safeContents == 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 8504678bd0c2e5..05631d3d26f279 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,10 +82,8 @@ 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 == 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 03fc39cb90f9c6..d5a9412a78986b 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,10 +55,8 @@ internal Pkcs12SafeContents(ContentInfoAsn contentInfoAsn) } } - public void AddSafeBag(Pkcs12SafeBag safeBag) + public void AddSafeBag(Pkcs12SafeBag safeBag!!) { - if (safeBag == null) - throw new ArgumentNullException(nameof(safeBag)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -70,10 +68,8 @@ public void AddSafeBag(Pkcs12SafeBag safeBag) _bags.Add(safeBag); } - public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) + public Pkcs12CertBag AddCertificate(X509Certificate2 certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -82,10 +78,8 @@ public Pkcs12CertBag AddCertificate(X509Certificate2 certificate) return bag; } - public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) + public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -95,10 +89,8 @@ public Pkcs12KeyBag AddKeyUnencrypted(AsymmetricAlgorithm key) return bag; } - public Pkcs12SafeContentsBag AddNestedContents(Pkcs12SafeContents safeContents) + public Pkcs12SafeContentsBag AddNestedContents(Pkcs12SafeContents safeContents!!) { - if (safeContents == null) - throw new ArgumentNullException(nameof(safeContents)); if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None) throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents)); if (IsReadOnly) @@ -122,12 +114,10 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( } public Pkcs12ShroudedKeyBag AddShroudedKey( - AsymmetricAlgorithm key, + AsymmetricAlgorithm key!!, ReadOnlySpan passwordBytes, PbeParameters pbeParameters) { - if (key == null) - throw new ArgumentNullException(nameof(key)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -150,12 +140,10 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( } public Pkcs12ShroudedKeyBag AddShroudedKey( - AsymmetricAlgorithm key, + AsymmetricAlgorithm key!!, ReadOnlySpan password, PbeParameters pbeParameters) { - if (key == null) - throw new ArgumentNullException(nameof(key)); if (IsReadOnly) throw new InvalidOperationException(SR.Cryptography_Pkcs12_SafeContentsIsReadOnly); @@ -165,11 +153,8 @@ public Pkcs12ShroudedKeyBag AddShroudedKey( return bag; } - public Pkcs12SecretBag AddSecret(Oid secretType, ReadOnlyMemory secretValue) + public Pkcs12SecretBag AddSecret(Oid secretType!!, ReadOnlyMemory secretValue) { - if (secretType == 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 8d9678d21490b1..5d97f99be065d3 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,14 +17,11 @@ public sealed class Pkcs8PrivateKeyInfo public ReadOnlyMemory PrivateKeyBytes { get; } public Pkcs8PrivateKeyInfo( - Oid algorithmId, + Oid algorithmId!!, ReadOnlyMemory? algorithmParameters, ReadOnlyMemory privateKey, bool skipCopies = false) { - if (algorithmId == null) - throw new ArgumentNullException(nameof(algorithmId)); - if (algorithmParameters?.Length > 0) { // Read to ensure that there is precisely one legally encoded value. @@ -51,11 +48,8 @@ private Pkcs8PrivateKeyInfo( Attributes = attributes; } - public static Pkcs8PrivateKeyInfo Create(AsymmetricAlgorithm privateKey) + public static Pkcs8PrivateKeyInfo Create(AsymmetricAlgorithm privateKey!!) { - if (privateKey == null) - throw new ArgumentNullException(nameof(privateKey)); - byte[] pkcs8 = privateKey.ExportPkcs8PrivateKey(); return Decode(pkcs8, out _, skipCopy: true); } @@ -94,11 +88,8 @@ public byte[] Encode() return writer.Encode(); } - public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) + public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters!!) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -111,11 +102,8 @@ public byte[] Encrypt(ReadOnlySpan password, PbeParameters pbeParameters) } } - public byte[] Encrypt(ReadOnlySpan passwordBytes, PbeParameters pbeParameters) + public byte[] Encrypt(ReadOnlySpan passwordBytes, PbeParameters pbeParameters!!) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -134,13 +122,10 @@ public bool TryEncode(Span destination, out int bytesWritten) public bool TryEncrypt( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -153,13 +138,10 @@ public bool TryEncrypt( public bool TryEncrypt( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == 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 b0696f9b9ec0bd..e9810d2af658db 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,10 +56,8 @@ internal Pkcs9AttributeObject(Oid oid) } } - public override void CopyFrom(AsnEncodedData asnEncodedData) + public override void CopyFrom(AsnEncodedData asnEncodedData!!) { - if (asnEncodedData == 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 4624b91bcd23f7..617fcb304e961d 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,11 +62,8 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) return octets.OctetStringToUnicode(); } - private static byte[] Encode(string documentDescription) + private static byte[] Encode(string documentDescription!!) { - if (documentDescription == 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 889c98010bf52a..5344eb70c3f267 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,11 +62,8 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) return octets.OctetStringToUnicode(); } - private static byte[] Encode(string documentName) + private static byte[] Encode(string documentName!!) { - if (documentName == 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 62397bdc0fba96..bbf8a92377b658 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,10 +54,8 @@ IEnumerator IEnumerable.GetEnumerator() return ((RecipientInfoCollection)this).GetEnumerator(); } - public void CopyTo(Array array, int index) + public void CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -71,10 +69,8 @@ public void CopyTo(Array array, int index) } } - public void CopyTo(RecipientInfo[] array, int index) + public void CopyTo(RecipientInfo[] array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); _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 e2f30dd54bb779..e834302c7b3aa7 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,18 +162,13 @@ 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 == 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 7d0d6b08cc50f3..b5773082db3706 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,15 +120,10 @@ public bool VerifySignatureForHash( public bool VerifySignatureForHash( ReadOnlySpan hash, - Oid hashAlgorithmId, + Oid hashAlgorithmId!!, [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { - if (hashAlgorithmId == null) - { - throw new ArgumentNullException(nameof(hashAlgorithmId)); - } - signerCertificate = null; X509Certificate2? cert = GetSignerCertificate(extraCandidates); @@ -152,15 +147,10 @@ public bool VerifySignatureForHash( } public bool VerifySignatureForSignerInfo( - SignerInfo signerInfo, + SignerInfo signerInfo!!, [NotNullWhen(true)] out X509Certificate2? signerCertificate, X509Certificate2Collection? extraCandidates = null) { - if (signerInfo == 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 f3e70b14d2a166..a1e54d08e9592e 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,11 +323,6 @@ private static byte[] Encode( ReadOnlyMemory? tsaName, X509ExtensionCollection? extensions) { - if (policyId == null) - throw new ArgumentNullException(nameof(policyId)); - if (hashAlgorithmId == 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 bc38187f6edc23..b5dc24bf3f20db 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 @@ -40,10 +40,8 @@ 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 == null) - throw new ArgumentNullException(nameof(contentInfo)); if (contentInfo.Content == null) throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "contentInfo.Content"), nameof(contentInfo)); @@ -158,11 +156,8 @@ public byte[] Encode() } } - public void Decode(byte[] encodedMessage) + public void Decode(byte[] encodedMessage!!) { - if (encodedMessage == null) - throw new ArgumentNullException(nameof(encodedMessage)); - Decode(new ReadOnlySpan(encodedMessage)); } @@ -298,13 +293,8 @@ 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 == 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. @@ -407,11 +397,8 @@ public void RemoveSignature(int index) UpdateMetadata(); } - public void RemoveSignature(SignerInfo signerInfo) + public void RemoveSignature(SignerInfo signerInfo!!) { - if (signerInfo == 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 9c7874b451c428..d216044736fa73 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 @@ -433,11 +433,8 @@ public void RemoveCounterSignature(int index) } } - public void RemoveCounterSignature(SignerInfo counterSignerInfo) + public void RemoveCounterSignature(SignerInfo counterSignerInfo!!) { - if (counterSignerInfo == null) - throw new ArgumentNullException(nameof(counterSignerInfo)); - SignerInfoCollection docSigners = _document.SignerInfos; int index = docSigners.FindIndexForSigner(this); @@ -460,11 +457,8 @@ 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 == 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 27193a75102844..fabde3dedb6a0e 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,10 +51,8 @@ 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 == 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 d67da72075b395..61e40cdde4da18 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,19 +14,13 @@ 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) { - if (userData == null) - throw new ArgumentNullException(nameof(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) { - if (encryptedData == null) - throw new ArgumentNullException(nameof(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 e55dd306cc0a50..5c9cc7e70a3ce7 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,11 +17,8 @@ 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 == null) - throw new ArgumentNullException(nameof(inputStream)); - _c14nDoc = new CanonicalXmlDocument(true, includeComments); _c14nDoc.XmlResolver = resolver; _c14nDoc.Load(Utils.PreProcessStreamInput(inputStream, resolver, strBaseUri)); @@ -29,22 +26,16 @@ internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver reso } 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 == 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 == 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 b634b00fae4d97..62b92652924afc 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,11 +22,8 @@ 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 == null) - throw new ArgumentNullException(nameof(node)); - XmlNodeList childNodes = node.ChildNodes; foreach (XmlNode childNode in childNodes) { @@ -46,11 +43,8 @@ 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 == 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 4283eed5cd3818..e03b4004a79f97 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,11 +90,8 @@ internal XmlElement GetXml(XmlDocument document) return cipherDataElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == 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 d8be38d6a3762f..04e7e8aaa9d8f3 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,11 +65,8 @@ public override XmlElement GetXml() return referenceElement; } - public override void LoadXml(XmlElement value) + public override void LoadXml(XmlElement value!!) { - if (value == 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 3eba3433590a95..f43b5de2c2dfbb 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,12 +138,8 @@ 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 == 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 498c97a31b25ac..146e1ccffe21dc 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,11 +23,8 @@ 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 == null) - throw new ArgumentNullException(nameof(data)); - _id = id; _mimeType = mimeType; _encoding = encoding; @@ -131,11 +128,8 @@ internal XmlElement GetXml(XmlDocument document) return objectElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == 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 9d085a5e3c2001..56e570ff6a84ad 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,11 +7,8 @@ namespace System.Security.Cryptography.Xml { public sealed class EncryptedData : EncryptedType { - public override void LoadXml(XmlElement value) + public override void LoadXml(XmlElement value!!) { - if (value == 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 a379d78f0b9b66..d57eb24215abe3 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,11 +59,8 @@ public void AddReference(KeyReference keyReference) ReferenceList.Add(keyReference); } - public override void LoadXml(XmlElement value) + public override void LoadXml(XmlElement value!!) { - if (value == 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 2e356d8df4aff0..8bbeffb18e99c9 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,11 +103,8 @@ internal XmlElement GetXml(XmlDocument document) return referenceElement; } - public virtual void LoadXml(XmlElement value) + public virtual void LoadXml(XmlElement value!!) { - if (value == 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 15315fd464eda9..4ea614d17c1fac 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,11 +178,8 @@ public string Recipient // private methods // - private byte[] GetCipherValue(CipherData cipherData) + private byte[] GetCipherValue(CipherData cipherData!!) { - if (cipherData == null) - throw new ArgumentNullException(nameof(cipherData)); - Stream inputStream = null; if (cipherData.CipherValue != null) @@ -264,11 +261,8 @@ 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 == 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) @@ -300,11 +294,8 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmet // 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 == null) - throw new ArgumentNullException(nameof(encryptedData)); - if (encryptedData.KeyInfo == null) return null; IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator(); @@ -385,10 +376,8 @@ 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 == null) - throw new ArgumentNullException(nameof(encryptedKey)); if (encryptedKey.KeyInfo == null) return null; @@ -504,13 +493,8 @@ 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 == null) - throw new ArgumentNullException(nameof(keyName)); - if (keyObject == null) - throw new ArgumentNullException(nameof(keyObject)); - if (!(keyObject is SymmetricAlgorithm) && !(keyObject is RSA)) throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); _keyNameMapping.Add(keyName, keyObject); @@ -523,13 +507,8 @@ 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 == null) - throw new ArgumentNullException(nameof(inputElement)); - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - using (RSA rsaPublicKey = certificate.GetRSAPublicKey()) { if (rsaPublicKey == null) @@ -563,13 +542,8 @@ public EncryptedData Encrypt(XmlElement inputElement, X509Certificate2 certifica // 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 == null) - throw new ArgumentNullException(nameof(inputElement)); - if (keyName == null) - throw new ArgumentNullException(nameof(keyName)); - object encryptionKey = null; if (_keyNameMapping != null) encryptionKey = _keyNameMapping[keyName]; @@ -664,13 +638,8 @@ public void DecryptDocument() } // encrypts the supplied arbitrary data - public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorithm) + public byte[] EncryptData(byte[] plaintext!!, SymmetricAlgorithm symmetricAlgorithm!!) { - if (plaintext == null) - throw new ArgumentNullException(nameof(plaintext)); - if (symmetricAlgorithm == null) - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - // save the original symmetric algorithm CipherMode origMode = symmetricAlgorithm.Mode; PaddingMode origPadding = symmetricAlgorithm.Padding; @@ -707,25 +676,15 @@ public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorith } // 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 == null) - throw new ArgumentNullException(nameof(inputElement)); - if (symmetricAlgorithm == 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 == null) - throw new ArgumentNullException(nameof(encryptedData)); - if (symmetricAlgorithm == null) - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - // get the cipher value and decrypt byte[] cipherValue = GetCipherValue(encryptedData.CipherData); @@ -766,13 +725,8 @@ public byte[] DecryptData(EncryptedData encryptedData, SymmetricAlgorithm symmet } // 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 == null) - throw new ArgumentNullException(nameof(inputElement)); - if (decryptedData == null) - throw new ArgumentNullException(nameof(decryptedData)); - XmlNode parent = inputElement.ParentNode; if (parent.NodeType == XmlNodeType.Document) { @@ -836,13 +790,8 @@ 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 == null) - throw new ArgumentNullException(nameof(inputElement)); - if (encryptedData == null) - throw new ArgumentNullException(nameof(encryptedData)); - // First, get the XML representation of the EncryptedData object XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument); switch (content) @@ -862,13 +811,8 @@ public static void ReplaceElement(XmlElement inputElement, EncryptedData encrypt } // 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 == null) - throw new ArgumentNullException(nameof(keyData)); - if (symmetricAlgorithm == null) - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - if (symmetricAlgorithm is TripleDES) { // CMS Triple DES Key Wrap @@ -888,13 +832,8 @@ public static byte[] EncryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgo // 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 == null) - throw new ArgumentNullException(nameof(keyData)); - if (rsa == null) - throw new ArgumentNullException(nameof(rsa)); - if (useOAEP) { RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa); @@ -908,13 +847,8 @@ 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 == null) - throw new ArgumentNullException(nameof(keyData)); - if (symmetricAlgorithm == null) - throw new ArgumentNullException(nameof(symmetricAlgorithm)); - if (symmetricAlgorithm is TripleDES) { // CMS Triple DES Key Wrap @@ -933,13 +867,8 @@ public static byte[] DecryptKey(byte[] keyData, SymmetricAlgorithm symmetricAlgo // 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 == null) - throw new ArgumentNullException(nameof(keyData)); - if (rsa == 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 215b5697720900..ee19948e7b7773 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,11 +77,8 @@ internal XmlElement GetXml(XmlDocument document) return encryptionMethodElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == 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 d2f901609718f0..e7e0c6131025c6 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,10 +15,8 @@ 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 == null) - throw new ArgumentNullException(nameof(elementProperty)); if (elementProperty.LocalName != "EncryptionProperty" || elementProperty.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl) throw new CryptographicException(SR.Cryptography_Xml_InvalidEncryptionProperty); @@ -73,10 +71,8 @@ internal XmlElement GetXml(XmlDocument document) return document.ImportNode(_elemProp, true) as XmlElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == 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 90dde6370104c0..723109d4214dee 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,33 +12,24 @@ 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 == 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 == 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 == 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 e69d101f1f907e..e50050440597b3 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,11 +58,8 @@ internal XmlElement GetXml(XmlDocument xmlDocument) return keyInfoElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == 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 47ed8746223438..217e3532f85967 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,10 +48,8 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) return nameElement; } - public override void LoadXml(XmlElement value) + public override void LoadXml(XmlElement value!!) { - if (value == 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 05af3036e01677..64fbea25761a54 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,11 +63,8 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) return retrievalMethodElement; } - public override void LoadXml(XmlElement value) + public override void LoadXml(XmlElement value!!) { - if (value == 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 545c42499cb856..5271eb57a3d662 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,11 +39,8 @@ public KeyInfoX509Data(X509Certificate cert) AddCertificate(cert); } - public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption) + public KeyInfoX509Data(X509Certificate cert!!, X509IncludeOption includeOption) { - if (cert == null) - throw new ArgumentNullException(nameof(cert)); - X509Certificate2 certificate = new X509Certificate2(cert); X509ChainElementCollection elements; X509Chain chain; @@ -100,11 +97,8 @@ public ArrayList Certificates get { return _certificates; } } - public void AddCertificate(X509Certificate certificate) + public void AddCertificate(X509Certificate certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - if (_certificates == null) _certificates = new ArrayList(); @@ -262,11 +256,8 @@ internal override XmlElement GetXml(XmlDocument xmlDocument) return x509DataElement; } - public override void LoadXml(XmlElement element) + public override void LoadXml(XmlElement element!!) { - if (element == 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 a0e8bd941c6fd0..45817f9184ebce 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,12 +93,8 @@ 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 == 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 581e8dc21afbda..3c19d1537dc23e 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,11 +205,8 @@ internal XmlElement GetXml(XmlDocument document) return referenceElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == 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); @@ -314,11 +311,8 @@ public void LoadXml(XmlElement value) _cachedXml = value; } - public void AddTransform(Transform transform) + public void AddTransform(Transform transform!!) { - if (transform == 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 263c789ae27551..6c4dc63a443179 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,11 +24,8 @@ public int Count get { return _references.Count; } } - public int Add(object value) + public int Add(object value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - if (!(value is DataReference) && !(value is KeyReference)) throw new ArgumentException(SR.Cryptography_Xml_IncorrectObjectType, nameof(value)); @@ -50,11 +47,8 @@ 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 == 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 f60c078778ccf3..7d97d7bf88d052 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,12 +133,8 @@ internal XmlElement GetXml(XmlDocument document) return signatureElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - // Make sure we don't get passed null - if (value == 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 fa61cdc33f864e..91ae7009eddffe 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,11 +197,8 @@ internal XmlElement GetXml(XmlDocument document) return signedInfoElement; } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - // SignedInfo XmlElement signedInfoElement = value; if (!signedInfoElement.LocalName.Equals("SignedInfo")) @@ -274,11 +271,8 @@ public void LoadXml(XmlElement value) _cachedXml = signedInfoElement; } - public void AddReference(Reference reference) + public void AddReference(Reference reference!!) { - if (reference == 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 fbedd3a907cdd9..48b75deec69584 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,17 +90,13 @@ public SignedXml() Initialize(null); } - public SignedXml(XmlDocument document) + public SignedXml(XmlDocument document!!) { - if (document == null) - throw new ArgumentNullException(nameof(document)); Initialize(document.DocumentElement); } - public SignedXml(XmlElement elem) + public SignedXml(XmlElement elem!!) { - if (elem == null) - throw new ArgumentNullException(nameof(elem)); Initialize(elem); } @@ -211,11 +207,8 @@ public XmlElement GetXml() return m_signature.GetXml(); } - public void LoadXml(XmlElement value) + public void LoadXml(XmlElement value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - m_signature.LoadXml(value); if (_context == null) @@ -418,11 +411,8 @@ public void ComputeSignature() m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); } - public void ComputeSignature(KeyedHashAlgorithm macAlg) + public void ComputeSignature(KeyedHashAlgorithm macAlg!!) { - if (macAlg == null) - throw new ArgumentNullException(nameof(macAlg)); - HMAC hash = macAlg as HMAC; if (hash == null) throw new CryptographicException(SR.Cryptography_Xml_SignatureMethodKeyMismatch); @@ -991,11 +981,8 @@ private bool CheckSignatureFormat() return formatValid; } - private bool CheckSignedInfo(AsymmetricAlgorithm key) + private bool CheckSignedInfo(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo); SignatureDescription signatureDescription = CryptoHelpers.CreateFromName(SignatureMethod); @@ -1023,11 +1010,8 @@ private bool CheckSignedInfo(AsymmetricAlgorithm key) return asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue); } - private bool CheckSignedInfo(KeyedHashAlgorithm macAlg) + private bool CheckSignedInfo(KeyedHashAlgorithm macAlg!!) { - if (macAlg == 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 b9bdf2401f8373..2b208fda41a54e 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,11 +176,8 @@ internal XmlElement GetXml(XmlDocument document, string ns) return transformsElement; } - internal void LoadXml(XmlElement value) + internal void LoadXml(XmlElement value!!) { - if (value == 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 2bbc23cc66612e..a3b766792701b6 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,21 +31,15 @@ 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 == 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 == null) - throw new ArgumentNullException(nameof(element)); - XmlNode ancestorNode = ((XmlNode)element).ParentNode; while (ancestorNode != null) { @@ -196,11 +190,8 @@ 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 == null) - throw new ArgumentNullException(nameof(document)); - MyXmlDocument doc = new MyXmlDocument(); doc.PreserveWhitespace = document.PreserveWhitespace; @@ -218,11 +209,8 @@ internal static XmlDocument PreProcessDocumentInput(XmlDocument document, XmlRes return doc; } - internal static XmlDocument PreProcessElementInput(XmlElement elem, XmlResolver xmlResolver, string baseUri) + internal static XmlDocument PreProcessElementInput(XmlElement elem!!, XmlResolver xmlResolver, string baseUri) { - if (elem == 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 9c7f1ff3682cbb..e7a4a6beab2cb5 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,10 +76,8 @@ public override Type[] OutputTypes get { return _outputTypes; } } - public void AddExceptUri(string uri) + public void AddExceptUri(string uri!!) { - if (uri == null) - throw new ArgumentNullException(nameof(uri)); ExceptUris.Add(uri); } @@ -157,10 +155,8 @@ private void LoadStreamInput(Stream stream) _encryptedDataList = document.SelectNodes("//enc:EncryptedData", _nsm); } - private void LoadXmlDocumentInput(XmlDocument document) + private void LoadXmlDocumentInput(XmlDocument document!!) { - if (document == 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 d4be6ffa73f0f6..2fac6deb654884 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,11 +89,8 @@ private void LoadStreamInput(Stream stream) _nsm.AddNamespace("dsig", SignedXml.XmlDsigNamespaceUrl); } - private void LoadXmlNodeListInput(XmlNodeList nodeList) + private void LoadXmlNodeListInput(XmlNodeList nodeList!!) { - // Empty node list is not acceptable - if (nodeList == null) - throw new ArgumentNullException(nameof(nodeList)); _containingDocument = Utils.GetOwnerDocument(nodeList); if (_containingDocument == null) throw new CryptographicException(SR.Cryptography_Xml_EnvelopedSignatureRequiresContext); @@ -103,10 +100,8 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) _inputNodeList = nodeList; } - private void LoadXmlDocumentInput(XmlDocument doc) + private void LoadXmlDocumentInput(XmlDocument doc!!) { - if (doc == 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 9808e723e2a0bc..aa79115fd978ab 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,11 +72,9 @@ protected SafeNCryptHandle() : base(true) } [SupportedOSPlatform("windows")] - protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle) + protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle!!) : base(true) { - if (parentHandle == null) - throw new ArgumentNullException(nameof(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.csproj b/src/libraries/System.Security.Cryptography/src/System.Security.Cryptography.csproj index 073513a0de966d..0e12e3d1b3def2 100644 --- a/src/libraries/System.Security.Cryptography/src/System.Security.Cryptography.csproj +++ b/src/libraries/System.Security.Cryptography/src/System.Security.Cryptography.csproj @@ -273,7 +273,6 @@ - diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AeadCommon.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AeadCommon.cs deleted file mode 100644 index d2e9320e3e87f4..00000000000000 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AeadCommon.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Internal.Cryptography; - -namespace System.Security.Cryptography -{ - internal static partial class AeadCommon - { - public static void CheckArgumentsForNull( - byte[] nonce, - byte[] plaintext, - byte[] ciphertext, - byte[] tag) - { - if (nonce == null) - throw new ArgumentNullException(nameof(nonce)); - - if (plaintext == null) - throw new ArgumentNullException(nameof(plaintext)); - - if (ciphertext == null) - throw new ArgumentNullException(nameof(ciphertext)); - - if (tag == null) - throw new ArgumentNullException(nameof(tag)); - } - } -} 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 de01bd16773e7f..98b49e12766d82 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 @@ -26,16 +26,14 @@ public AesCcm(byte[] key) { ThrowIfNotSupported(); - if (key == null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); AesAEAD.CheckKeySize(key.Length); 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) { - AeadCommon.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag); Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -50,9 +48,8 @@ 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) { - AeadCommon.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag); 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 c4ae2cc689a34e..3dca06a54f5124 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 @@ -27,16 +27,14 @@ public AesGcm(byte[] key) { ThrowIfNotSupported(); - if (key == null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); AesAEAD.CheckKeySize(key.Length); 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) { - AeadCommon.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag); Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -51,9 +49,8 @@ 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) { - AeadCommon.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag); 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 9b413892203448..98c0bf9f4d6b04 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,13 +178,10 @@ protected override bool TryEncryptCfbCore( } } - private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encrypting) + private ICryptoTransform CreateTransform(byte[] rgbKey!!, byte[]? rgbIV, bool encrypting) { // note: rbgIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) - throw new ArgumentNullException(nameof(rgbKey)); - long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(this.LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); 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 0a1555d698c9d8..7aab67d8b7341f 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,10 +32,8 @@ public AsnEncodedData(ReadOnlySpan rawData) Reset(null, rawData); } - public AsnEncodedData(AsnEncodedData asnEncodedData) + public AsnEncodedData(AsnEncodedData asnEncodedData!!) { - if (asnEncodedData == null) - throw new ArgumentNullException(nameof(asnEncodedData)); Reset(asnEncodedData._oid, asnEncodedData._rawData); } @@ -102,10 +100,8 @@ public byte[] RawData } } - public virtual void CopyFrom(AsnEncodedData asnEncodedData) + public virtual void CopyFrom(AsnEncodedData asnEncodedData!!) { - if (asnEncodedData == null) - throw new ArgumentNullException(nameof(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 a726efe6850430..396fc8447e35be 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,20 +21,15 @@ public AsnEncodedDataCollection(AsnEncodedData asnEncodedData) _list.Add(asnEncodedData); } - public int Add(AsnEncodedData asnEncodedData) + public int Add(AsnEncodedData asnEncodedData!!) { - if (asnEncodedData == null) - throw new ArgumentNullException(nameof(asnEncodedData)); - int indexOfNewItem = _list.Count; _list.Add(asnEncodedData); return indexOfNewItem; } - public void Remove(AsnEncodedData asnEncodedData) + public void Remove(AsnEncodedData asnEncodedData!!) { - if (asnEncodedData == null) - throw new ArgumentNullException(nameof(asnEncodedData)); _list.Remove(asnEncodedData); } @@ -64,10 +59,8 @@ IEnumerator IEnumerable.GetEnumerator() return GetEnumerator(); } - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -82,13 +75,11 @@ void ICollection.CopyTo(Array array, int index) } } - public void CopyTo(AsnEncodedData[] array, int index) + public void CopyTo(AsnEncodedData[] array!!, int index) { // Need to do part of the argument validation ourselves as AsnEncodedDataCollection throws // ArgumentOutOfRangeException where List<>.CopyTo() throws ArgumentException. - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); 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 2cd815e66dec61..a47c6d8dca0e94 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,11 +12,8 @@ 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) { - if (hash == null) - throw new ArgumentNullException(nameof(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 4fd2bd0869004e..1b3dbca3950153 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,11 +12,8 @@ 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!!) { - if (hash == null) - throw new ArgumentNullException(nameof(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.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CapiHelper.Windows.cs index 591470ad24e922..b40e7c67f55e3b 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,11 +1048,8 @@ 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!!) { - if (hashAlg == null) - throw new ArgumentNullException(nameof(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 e08762d0bfb642..3ec803bcba92fe 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,13 +27,10 @@ public ChaCha20Poly1305(ReadOnlySpan key) ImportKey(key); } - public ChaCha20Poly1305(byte[] key) + public ChaCha20Poly1305(byte[] key!!) { ThrowIfNotSupported(); - if (key == null) - throw new ArgumentNullException(nameof(key)); - CheckKeySize(key.Length); ImportKey(key); } @@ -46,9 +43,8 @@ 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) { - AeadCommon.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag); Encrypt((ReadOnlySpan)nonce, plaintext, ciphertext, tag, associatedData); } @@ -63,9 +59,8 @@ 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) { - AeadCommon.CheckArgumentsForNull(nonce, plaintext, ciphertext, tag); Decrypt((ReadOnlySpan)nonce, ciphertext, tag, plaintext, associatedData); } 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 ff1ba4a7c83380..34980a84e07385 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,14 +32,8 @@ 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) { - if (keyName == null) - throw new ArgumentNullException(nameof(keyName)); - - if (provider == null) - throw new ArgumentNullException(nameof(provider)); - using (SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider()) { SafeNCryptKeyHandle? keyHandle = null; 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 4a7e64000cbd92..9a7cc942199c9d 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,28 +102,20 @@ ref MemoryMarshal.GetReference(keyBlob), } internal static CngKey Import( - byte[] keyBlob, + byte[] keyBlob!!, string? curveName, CngKeyBlobFormat format, CngProvider provider) { - if (keyBlob == null) - throw new ArgumentNullException(nameof(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!!) { - if (format == null) - throw new ArgumentNullException(nameof(format)); - if (provider == null) - throw new ArgumentNullException(nameof(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 4f6344baf2a514..b2933879c8a5f1 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,13 +32,8 @@ 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) { - if (keyName == null) - throw new ArgumentNullException(nameof(keyName)); - if (provider == null) - throw new ArgumentNullException(nameof(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 51a70f8d9468b1..968e94627adc8b 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,10 +15,8 @@ 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) { - if (keyHandle == null) - throw new ArgumentNullException(nameof(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 4507c0fccf48f6..d20f7fe9522f2e 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,11 +15,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - byte[]? value = _keyHandle.GetProperty(name, options); if (value == null) throw ErrorCode.NTE_NOT_FOUND.ToCryptographicException(); @@ -33,11 +30,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(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 329c581d765152..83f4dcf7dbe508 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,12 +16,9 @@ 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() { - if (name == null) - throw new ArgumentNullException(nameof(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 654a06a95e5588..ed96d10154a32b 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,13 +27,8 @@ 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) { - if (keyName == null) - throw new ArgumentNullException(nameof(keyName)); - if (provider == null) - throw new ArgumentNullException(nameof(provider)); - _outer = outer; _keyName = keyName; @@ -138,11 +133,8 @@ public UniversalCryptoTransform CreateCryptoTransform(byte[]? iv, bool encryptin return CreatePersistedCryptoTransformCore(ProduceCngKey, iv, encrypting, padding, mode, feedbackSizeInBits); } - 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) { - if (rgbKey == null) - throw new ArgumentNullException(nameof(rgbKey)); - ValidateFeedbackSize(mode, feedbackSizeInBits); byte[] key = rgbKey.CloneByteArray(); 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 e03c5e3756dc18..1f05cf20b8331f 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 @@ -306,12 +306,10 @@ public static void AddAlgorithm(Type algorithm, params string[] names) #if BROWSER throw new PlatformNotSupportedException(SR.SystemSecurityCryptography_PlatformNotSupported); #else - if (algorithm == null) - throw new ArgumentNullException(nameof(algorithm)); + ArgumentNullException.ThrowIfNull(algorithm); if (!algorithm.IsVisible) throw new ArgumentException(SR.Cryptography_AlgorithmTypesMustBeVisible, nameof(algorithm)); - if (names == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(names); string[] algorithmNames = new string[names.Length]; Array.Copy(names, algorithmNames, algorithmNames.Length); @@ -335,11 +333,8 @@ 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) { - if (name == null) - throw new ArgumentNullException(nameof(name)); - #if BROWSER switch (name) { @@ -494,10 +489,8 @@ public static void AddOID(string oid, params string[] names) #if BROWSER throw new PlatformNotSupportedException(SR.SystemSecurityCryptography_PlatformNotSupported); #else - if (oid == null) - throw new ArgumentNullException(nameof(oid)); - if (names == null) - throw new ArgumentNullException(nameof(names)); + ArgumentNullException.ThrowIfNull(oid); + ArgumentNullException.ThrowIfNull(names); string[] oidNames = new string[names.Length]; Array.Copy(names, oidNames, oidNames.Length); @@ -526,8 +519,7 @@ public static void AddOID(string oid, params string[] names) #if BROWSER throw new PlatformNotSupportedException(SR.SystemSecurityCryptography_PlatformNotSupported); #else - if (name == null) - throw new ArgumentNullException(nameof(name)); + ArgumentNullException.ThrowIfNull(name); appOidHT.TryGetValue(name, out string? oidName); @@ -552,8 +544,7 @@ public static byte[] EncodeOID(string str) #if BROWSER throw new PlatformNotSupportedException(SR.SystemSecurityCryptography_PlatformNotSupported); #else - if (str == null) - throw new ArgumentNullException(nameof(str)); + ArgumentNullException.ThrowIfNull(str); string[] oidString = str.Split('.'); // valid ASN.1 separator uint[] oidNums = new uint[oidString.Length]; 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 e3cb8b85b3bdaf..25678e56ac838a 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,13 +35,8 @@ 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) { - if (transform is null) - { - throw new ArgumentNullException(nameof(transform)); - } - _stream = stream; _transform = transform; _leaveOpen = leaveOpen; @@ -719,11 +714,8 @@ 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) { - if (destination is null) - throw new ArgumentNullException(nameof(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 3dd55e352f74a1..8b1415ba8289f5 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,13 +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) { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) - throw new ArgumentNullException(nameof(rgbKey)); - long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); 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 0990807ceed7ad..707a62213ef532 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 @@ -95,10 +95,8 @@ protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) throw DerivedClassMustOverride(); } - public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) + public byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm) { - if (data == null) - throw new ArgumentNullException(nameof(data)); // hashAlgorithm is verified in the overload return SignData(data, 0, data.Length, hashAlgorithm); @@ -125,9 +123,8 @@ 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); @@ -135,9 +132,8 @@ public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatur 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) @@ -185,13 +181,12 @@ public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithm /// 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) @@ -234,9 +229,8 @@ 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); @@ -264,9 +258,8 @@ 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); @@ -292,13 +285,8 @@ 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) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - return VerifyData(data, 0, data.Length, signature, hashAlgorithm); } @@ -374,10 +362,8 @@ 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); @@ -401,10 +387,8 @@ public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName /// /// An error occurred in the signing operation. /// - public byte[] CreateSignature(byte[] rgbHash, DSASignatureFormat signatureFormat) + public byte[] CreateSignature(byte[] rgbHash!!, DSASignatureFormat signatureFormat) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -641,13 +625,11 @@ 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); @@ -678,13 +660,11 @@ 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); @@ -787,12 +767,8 @@ 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) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(rgbSignature)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -906,13 +882,10 @@ private static Exception DerivedClassMustOverride() => public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan.Empty, @@ -930,13 +903,10 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 4bdd219dfb8f64..b158cd76619e06 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,11 +20,8 @@ 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!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 252f93272e783f..9a62c5f90f6aaa 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,10 +226,8 @@ 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) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); if (rgbHash.Length != SHA1_HASHSIZE) @@ -245,13 +243,8 @@ 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!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(rgbSignature)); - // For compat with Windows, no check for rgbHash.Length != SHA1_HASHSIZE // Only SHA1 allowed; the default value is SHA1 @@ -297,11 +290,8 @@ 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!!) { - if (keyBlob == null) - throw new ArgumentNullException(nameof(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 99525802e1ebd6..afbfb5500c7b0e 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,10 +478,8 @@ 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) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -506,13 +504,8 @@ 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!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(rgbSignature)); - int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); return CapiHelper.VerifySign( @@ -527,13 +520,8 @@ 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!!) { - if (keyBlob == null) - { - throw new ArgumentNullException(nameof(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 6847a0a1f56a75..add003a1273889 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,10 +36,8 @@ public DSAOpenSsl(DSAParameters parameters) [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public DSAOpenSsl(SafeEvpPKeyHandle pkeyHandle) + public DSAOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) { - if (pkeyHandle == null) - throw new ArgumentNullException(nameof(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 8bc3023057a26a..7843f4e7505918 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,19 +9,13 @@ public class DSASignatureDeformatter : AsymmetricSignatureDeformatter public DSASignatureDeformatter() { } - public DSASignatureDeformatter(AsymmetricAlgorithm key) : this() + public DSASignatureDeformatter(AsymmetricAlgorithm key!!) : this() { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _dsaKey = (DSA)key; } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _dsaKey = (DSA)key; } @@ -34,12 +28,8 @@ public override void SetHashAlgorithm(string strName) } } - public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) + public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(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 9e2a9ef0aa376a..80575403ac50ff 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,19 +9,13 @@ public class DSASignatureFormatter : AsymmetricSignatureFormatter public DSASignatureFormatter() { } - public DSASignatureFormatter(AsymmetricAlgorithm key) : this() + public DSASignatureFormatter(AsymmetricAlgorithm key!!) : this() { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _dsaKey = (DSA)key; } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _dsaKey = (DSA)key; } @@ -34,10 +28,8 @@ public override void SetHashAlgorithm(string strName) } } - public override byte[] CreateSignature(byte[] rgbHash) + public override byte[] CreateSignature(byte[] rgbHash!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(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 d22e7d79725f7c..dd73c5d6f57970 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,13 +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) { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) - throw new ArgumentNullException(nameof(rgbKey)); - long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); 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 d5c34e18d9fb01..3926fa6adbcaa2 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,13 +121,10 @@ public virtual void GenerateKey(ECCurve curve) /// public override unsafe bool TryExportEncryptedPkcs8PrivateKey( 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, @@ -194,13 +191,10 @@ public override unsafe bool TryExportEncryptedPkcs8PrivateKey( /// public override unsafe bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 5876e483bcb6de..1bf183b59c830a 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 @@ -103,12 +103,8 @@ 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!!) { - if (oidFriendlyName == null) - { - throw new ArgumentNullException(nameof(oidFriendlyName)); - } return ECCurve.CreateFromValueAndName(null, oidFriendlyName); } @@ -117,12 +113,8 @@ 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!!) { - if (oidValue == null) - { - throw new ArgumentNullException(nameof(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 c0bfb6f798953d..7040290e496c87 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,13 +32,8 @@ 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!!) { - if (algorithm == null) - { - throw new ArgumentNullException(nameof(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 deca9cfd932eeb..84082e23bb507e 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,11 +8,8 @@ namespace System.Security.Cryptography { public sealed partial class ECDiffieHellmanCng : ECDiffieHellman { - public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) + public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); - if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) { using (CngKey import = otherKey.Import()) @@ -40,10 +37,8 @@ public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPubl } } - public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey) + public byte[] DeriveKeyMaterial(CngKey otherPartyPublicKey!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); if (otherPartyPublicKey.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(otherPartyPublicKey)); if (otherPartyPublicKey.KeySize != KeySize) @@ -96,11 +91,8 @@ 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!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(otherPartyPublicKey)); - if (otherPartyPublicKey is ECDiffieHellmanCngPublicKey otherKey) { using (CngKey importedKey = otherKey.Import()) @@ -126,10 +118,8 @@ public SafeNCryptSecretHandle DeriveSecretAgreementHandle(ECDiffieHellmanPublicK /// /// Get a handle to the secret agreement between two parties /// - public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey) + public SafeNCryptSecretHandle DeriveSecretAgreementHandle(CngKey otherPartyPublicKey!!) { - if (otherPartyPublicKey == null) - throw new ArgumentNullException(nameof(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 f4a574a67dcc38..9e88e2c0db8dc1 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,11 +20,8 @@ public sealed partial class ECDiffieHellmanCng : ECDiffieHellman private byte[]? _seed; [SupportedOSPlatform("windows")] - public ECDiffieHellmanCng(CngKey key) + public ECDiffieHellmanCng(CngKey key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - if (key.AlgorithmGroup != CngAlgorithmGroup.ECDiffieHellman) throw new ArgumentException(SR.Cryptography_ArgECDHRequiresECDHKey, nameof(key)); @@ -43,10 +40,7 @@ public CngAlgorithm HashAlgorithm set { - if (_hashAlgorithm == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value, nameof(value)); _hashAlgorithm = value; } 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 886e5161f0af0c..979f24305cc588 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 @@ -59,13 +59,8 @@ 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!!) { - if (publicKeyBlob == null) - throw new ArgumentNullException(nameof(publicKeyBlob)); - if (format == null) - throw new ArgumentNullException(nameof(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 870e7291563a60..f3baa43a7a208c 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,10 +22,8 @@ public sealed partial class ECDiffieHellmanOpenSsl : ECDiffieHellman [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public ECDiffieHellmanOpenSsl(SafeEvpPKeyHandle pkeyHandle) + public ECDiffieHellmanOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) { - if (pkeyHandle == null) - throw new ArgumentNullException(nameof(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 eb72cb592deae3..26fb83ebc9f67e 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 @@ -15,13 +15,8 @@ protected ECDiffieHellmanPublicKey() _keyBlob = Array.Empty(); } - protected ECDiffieHellmanPublicKey(byte[] keyBlob) + protected ECDiffieHellmanPublicKey(byte[] keyBlob!!) { - if (keyBlob == null) - { - throw new ArgumentNullException(nameof(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 735230cb2a9d95..bfeb7d190f5d2a 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,28 +30,20 @@ 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!!) { - if (algorithm == null) - { - throw new ArgumentNullException(nameof(algorithm)); - } - return CryptoConfig.CreateFromName(algorithm) as ECDsa; } - public virtual byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm) + public virtual byte[] SignData(byte[] data!!, HashAlgorithmName hashAlgorithm) { - if (data == null) - throw new ArgumentNullException(nameof(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) @@ -99,13 +91,12 @@ public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithm /// 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) @@ -194,9 +185,8 @@ 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); @@ -225,9 +215,8 @@ public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, DSASignatur /// /// 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); @@ -273,10 +262,8 @@ 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) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); if (!signatureFormat.IsKnownValue()) throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat); @@ -419,20 +406,16 @@ 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) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - return VerifyData(data, 0, data.Length, signature, hashAlgorithm); } @@ -534,10 +517,8 @@ 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); @@ -619,10 +600,8 @@ 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); @@ -652,13 +631,11 @@ public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgo /// 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); @@ -829,12 +806,8 @@ 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) { - if (hash == null) - throw new ArgumentNullException(nameof(hash)); - if (signature == null) - throw new ArgumentNullException(nameof(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 597f077883686b..2c503dab17a0ed 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 @@ -37,11 +37,8 @@ public CngAlgorithm HashAlgorithm /// if is not an ECDsa key /// if is null. [SupportedOSPlatform("windows")] - public ECDsaCng(CngKey key) + public ECDsaCng(CngKey key!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 aeac93ad1637f3..e45bb748e8232c 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,10 +22,8 @@ public sealed partial class ECDsaOpenSsl : ECDsa [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public ECDsaOpenSsl(SafeEvpPKeyHandle pkeyHandle) + public ECDsaOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) { - if (pkeyHandle == null) - throw new ArgumentNullException(nameof(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 5c883c6e64acd8..6d3b9bf593c054 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,11 +25,8 @@ 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) { - if (ikm == null) - throw new ArgumentNullException(nameof(ikm)); - int hashLength = HashLength(hashAlgorithmName); byte[] prk = new byte[hashLength]; @@ -82,11 +79,8 @@ 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) { - if (prk == null) - throw new ArgumentNullException(nameof(prk)); - if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); @@ -208,11 +202,8 @@ 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) { - if (ikm == null) - throw new ArgumentNullException(nameof(ikm)); - if (outputLength <= 0) throw new ArgumentOutOfRangeException(nameof(outputLength), SR.ArgumentOutOfRange_NeedPosNum); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMAC.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMAC.cs index 779c6c00cbb9c0..55a0ad0b688ad2 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMAC.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMAC.cs @@ -31,10 +31,7 @@ public string HashName get => _hashName; set { - if (value == null) - { - throw new ArgumentNullException(nameof(HashName)); - } + ArgumentNullException.ThrowIfNull(value, nameof(HashName)); // On the desktop, setting the HashName selects (or switches over to) a new hashing algorithm via CryptoConfig. // Our intended refactoring turns HMAC back into an abstract class with no algorithm-specific implementation. 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 eff5baa635b8d6..6c9f0c6f58736e 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,13 +33,8 @@ public HMACMD5() { } - public HMACMD5(byte[] key) + public HMACMD5(byte[] key!!) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - this.HashName = HashAlgorithmNames.MD5; _hMacCommon = new HMACCommon(HashAlgorithmNames.MD5, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -91,13 +86,8 @@ 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!!) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -185,10 +175,8 @@ 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)); @@ -210,10 +198,8 @@ public static int HashData(ReadOnlySpan key, Stream source, Span des /// /// 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)); @@ -232,9 +218,8 @@ 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); } @@ -254,10 +239,8 @@ 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)); @@ -280,10 +263,8 @@ 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); } @@ -313,12 +294,10 @@ public static ValueTask HashDataAsync(byte[] key, Stream source, Cancell /// 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 cc8d5619da2084..38e724fcc963d6 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,13 +34,8 @@ public HMACSHA1() { } - public HMACSHA1(byte[] key) + public HMACSHA1(byte[] key!!) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - this.HashName = HashAlgorithmNames.SHA1; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA1, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -99,13 +94,8 @@ 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!!) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -193,10 +183,8 @@ 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)); @@ -218,10 +206,8 @@ public static int HashData(ReadOnlySpan key, Stream source, Span des /// /// 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)); @@ -240,9 +226,8 @@ 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); } @@ -262,10 +247,8 @@ 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)); @@ -288,10 +271,8 @@ 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); } @@ -321,12 +302,10 @@ public static ValueTask HashDataAsync(byte[] key, Stream source, Cancell /// 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 797f60dd3b49b0..30e992f2aa5481 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,13 +33,8 @@ public HMACSHA256() { } - public HMACSHA256(byte[] key) + public HMACSHA256(byte[] key!!) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - this.HashName = HashAlgorithmNames.SHA256; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA256, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -91,13 +86,8 @@ 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!!) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -185,10 +175,8 @@ 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)); @@ -210,10 +198,8 @@ public static int HashData(ReadOnlySpan key, Stream source, Span des /// /// 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)); @@ -232,9 +218,8 @@ 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); } @@ -254,10 +239,8 @@ 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)); @@ -280,10 +263,8 @@ 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); } @@ -313,12 +294,10 @@ public static ValueTask HashDataAsync(byte[] key, Stream source, Cancell /// 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 1162850933c35e..0cac6c6b3e1250 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,13 +33,8 @@ public HMACSHA384() { } - public HMACSHA384(byte[] key) + public HMACSHA384(byte[] key!!) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - this.HashName = HashAlgorithmNames.SHA384; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA384, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -108,13 +103,8 @@ 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!!) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -202,10 +192,8 @@ 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)); @@ -227,10 +215,8 @@ public static int HashData(ReadOnlySpan key, Stream source, Span des /// /// 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)); @@ -249,9 +235,8 @@ 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); } @@ -271,10 +256,8 @@ 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)); @@ -297,10 +280,8 @@ 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); } @@ -330,12 +311,10 @@ public static ValueTask HashDataAsync(byte[] key, Stream source, Cancell /// 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 079798b459a2b7..954ad903a5b058 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,13 +33,8 @@ public HMACSHA512() { } - public HMACSHA512(byte[] key) + public HMACSHA512(byte[] key!!) { - if (key is null) - { - throw new ArgumentNullException(nameof(key)); - } - this.HashName = HashAlgorithmNames.SHA512; _hMacCommon = new HMACCommon(HashAlgorithmNames.SHA512, key, BlockSize); base.Key = _hMacCommon.ActualKey!; @@ -105,13 +100,8 @@ 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!!) { - if (key is null) - throw new ArgumentNullException(nameof(key)); - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(key), new ReadOnlySpan(source)); } @@ -199,10 +189,8 @@ 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)); @@ -224,10 +212,8 @@ public static int HashData(ReadOnlySpan key, Stream source, Span des /// /// 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)); @@ -246,9 +232,8 @@ 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); } @@ -268,10 +253,8 @@ 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)); @@ -294,10 +277,8 @@ 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); } @@ -327,12 +308,10 @@ public static ValueTask HashDataAsync(byte[] key, Stream source, Cancell /// 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 b49d29bd4ad7ca..b816674e858516 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 @@ -45,8 +45,7 @@ public byte[] ComputeHash(byte[] buffer) { if (_disposed) throw new ObjectDisposedException(null); - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); + ArgumentNullException.ThrowIfNull(buffer); HashCore(buffer, 0, buffer.Length); return CaptureHashCodeAndReinitialize(); @@ -78,10 +77,8 @@ 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) { - if (buffer == null) - throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > buffer.Length)) @@ -123,11 +120,9 @@ public byte[] ComputeHash(Stream inputStream) } public Task ComputeHashAsync( - Stream inputStream, + Stream inputStream!!, CancellationToken cancellationToken = default) { - if (inputStream == null) - throw new ArgumentNullException(nameof(inputStream)); if (_disposed) throw new ObjectDisposedException(null); @@ -240,10 +235,8 @@ 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) { - if (inputBuffer == null) - throw new ArgumentNullException(nameof(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 07e332f82f384f..ae5ac7ae45d8f2 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,13 +121,8 @@ public override int GetHashCode() /// /// is null. /// - public static bool TryFromOid(string oidValue, out HashAlgorithmName value) + public static bool TryFromOid(string oidValue!!, out HashAlgorithmName value) { - if (oidValue is null) - { - throw new ArgumentNullException(nameof(oidValue)); - } - switch (oidValue) { case Oids.Md5: 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 23fbadceab2554..b33c4d7477377a 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,11 +56,8 @@ 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!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - AppendData(new ReadOnlySpan(data)); } @@ -84,10 +81,8 @@ 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) { - if (data == null) - throw new ArgumentNullException(nameof(data)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > data.Length)) @@ -347,11 +342,8 @@ 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!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 c1ba826d593559..edbb9b610f1b3f 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,11 +48,8 @@ protected MD5() /// /// is . /// - public static byte[] HashData(byte[] source) + public static byte[] HashData(byte[] source!!) { - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(source)); } @@ -134,10 +131,8 @@ 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)); @@ -158,10 +153,8 @@ 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)); @@ -183,10 +176,8 @@ 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)); @@ -217,12 +208,10 @@ public static ValueTask HashDataAsync(Stream source, CancellationToken c ///

/// 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 c3f6a28ff077b9..3ec5be3a97f6a8 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,23 +32,16 @@ public Oid(string? value, string? friendlyName) _hasInitializedFriendlyName = friendlyName != null; } - public Oid(Oid oid) + public Oid(Oid oid!!) { - if (oid == null) - throw new ArgumentNullException(nameof(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) { - if (friendlyName == null) - { - throw new ArgumentNullException(nameof(friendlyName)); - } - string? oidValue = OidLookup.ToOid(friendlyName, group, fallBackToAllGroups: false); if (oidValue == null) throw new CryptographicException(SR.Cryptography_Oid_InvalidName); @@ -56,11 +49,8 @@ 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) { - if (oidValue == null) - throw new ArgumentNullException(nameof(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 4b76860a983ba7..56c0c0c42d46f3 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,10 +66,8 @@ public Oid? this[string oid] IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - void ICollection.CopyTo(Array array, int index) + void ICollection.CopyTo(Array array!!, int index) { - if (array == null) - throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0 || index >= array.Length) @@ -84,13 +82,10 @@ void ICollection.CopyTo(Array array, int index) } } - public void CopyTo(Oid[] array, int index) + public void CopyTo(Oid[] array!!, int index) { // Need to do part of the argument validation ourselves as OidCollection throws // ArgumentOutOfRangeException where List<>.CopyTo() throws ArgumentException. - - if (array == null) - throw new ArgumentNullException(nameof(array)); if (index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); 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 fd96651c342fbd..17031b902e7c59 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,11 +18,8 @@ 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) { - if (oid == null) - throw new ArgumentNullException(nameof(oid)); - string? mappedName; bool shouldUseCache = ShouldUseCache(oidGroup); @@ -57,10 +54,8 @@ 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) { - if (friendlyName == null) - throw new ArgumentNullException(nameof(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 79cc9ecd83b642..597b47f4a14f8a 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,13 +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) { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) - throw new ArgumentNullException(nameof(rgbKey)); - if (!ValidKeySize(rgbKey.Length)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); 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 da0a5aedd5b2f9..eb09a9d09f7599 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 @@ -151,13 +151,8 @@ 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) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } - return SignData(data, 0, data.Length, hashAlgorithm, padding); } @@ -205,11 +200,8 @@ 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) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } @@ -372,13 +364,10 @@ private unsafe AsnWriter WritePkcs8PrivateKey() public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan password, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(pbeParameters)); - PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, @@ -396,13 +385,10 @@ public override bool TryExportEncryptedPkcs8PrivateKey( public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan passwordBytes, - PbeParameters pbeParameters, + PbeParameters pbeParameters!!, Span destination, out int bytesWritten) { - if (pbeParameters == null) - throw new ArgumentNullException(nameof(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 6038ea68ce7e14..f51f993a3c45d3 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,11 +20,8 @@ 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!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 70ba680b3f6fdd..636d917c9dc890 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,11 +40,8 @@ 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) { - if (rgb == null) - throw new ArgumentNullException(nameof(rgb)); - // size check -- must be exactly the modulus size if (rgb.Length != (KeySize / 8)) throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); @@ -52,23 +49,16 @@ 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!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(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) { - if (padding == null) - throw new ArgumentNullException(nameof(padding)); if (data.Length != (KeySize / 8)) throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize); if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) @@ -86,31 +76,21 @@ protected override void Dispose(bool disposing) } } - public byte[] Encrypt(byte[] rgb, bool fOAEP) + public byte[] Encrypt(byte[] rgb!!, bool fOAEP) { - if (rgb == null) - throw new ArgumentNullException(nameof(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!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(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) { - if (padding == null) - throw new ArgumentNullException(nameof(padding)); if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1) throw PaddingModeNotSupported(); @@ -190,18 +170,15 @@ 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 == null ? throw new ArgumentNullException(nameof(padding)) : + public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.SignData(data, hashAlgorithm, padding); - public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(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); - public override bool TrySignData(ReadOnlySpan data, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) => - padding == null ? throw new ArgumentNullException(nameof(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); @@ -214,20 +191,16 @@ 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 == null ? throw new ArgumentNullException(nameof(padding)) : + public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.SignHash(hash, hashAlgorithm, padding); - public override bool TrySignHash(ReadOnlySpan hash, Span destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) => - padding == null ? throw new ArgumentNullException(nameof(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 byte[] SignHash(byte[] rgbHash, string str) + public byte[] SignHash(byte[] rgbHash!!, string str) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -240,46 +213,25 @@ 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 == null ? throw new ArgumentNullException(nameof(padding)) : + 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(ReadOnlySpan data, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(padding)) : + public override bool VerifyData(ReadOnlySpan data, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding!!) => padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() : _impl.VerifyData(data, signature, hashAlgorithm, padding); - public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) + public override bool VerifyHash(byte[] hash!!, byte[] signature!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { - if (hash == null) - { - throw new ArgumentNullException(nameof(hash)); - } - if (signature == null) - { - throw new ArgumentNullException(nameof(signature)); - } - return VerifyHash((ReadOnlySpan)hash, (ReadOnlySpan)signature, hashAlgorithm, padding); } - public override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => - padding == null ? throw new ArgumentNullException(nameof(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 bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature) + public bool VerifyHash(byte[] rgbHash!!, string str, byte[] rgbSignature!!) { - if (rgbHash == null) - { - throw new ArgumentNullException(nameof(rgbHash)); - } - if (rgbSignature == null) - { - throw new ArgumentNullException(nameof(rgbSignature)); - } - return VerifyHash( (ReadOnlySpan)rgbHash, (ReadOnlySpan)rgbSignature, CapiHelper.NameOrOidToHashAlgorithmName(str), RSASignaturePadding.Pkcs1); @@ -296,11 +248,8 @@ private static Exception PaddingModeNotSupported() /// /// find whether an RSA key blob is public. /// - private static bool IsPublic(byte[] keyBlob) + private static bool IsPublic(byte[] keyBlob!!) { - if (keyBlob == null) - throw new ArgumentNullException(nameof(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 ed045ea21a9ce7..ba10764a98a228 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,13 +261,8 @@ 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) { - if (rgb == null) - { - throw new ArgumentNullException(nameof(rgb)); - } - // Save the KeySize value to a local because it has non-trivial cost. int keySize = KeySize; @@ -319,13 +314,8 @@ 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) { - if (rgb == null) - { - throw new ArgumentNullException(nameof(rgb)); - } - if (fOAEP) { int rsaSize = (KeySize + 7) / 8; @@ -484,10 +474,8 @@ 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) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); if (PublicOnly) throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); @@ -530,13 +518,8 @@ 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!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(rgbSignature)); - int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm); return VerifyHash(rgbHash, calgHash, rgbSignature); } @@ -558,12 +541,8 @@ 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!!) { - if (keyBlob == null) - { - throw new ArgumentNullException(nameof(keyBlob)); - } // The CAPI RSA public key representation consists of the following sequence: // - BLOBHEADER // - RSAPUBKEY @@ -630,13 +609,8 @@ 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!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(padding)); - if (padding == RSAEncryptionPadding.Pkcs1) { return Encrypt(data, fOAEP: false); @@ -651,13 +625,8 @@ public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) } } - public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) + public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!) { - if (data == null) - throw new ArgumentNullException(nameof(data)); - if (padding == null) - throw new ArgumentNullException(nameof(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 668d0784db8a95..4895e87d05ae83 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,11 +8,8 @@ public class RSAOAEPKeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter private RSA? _rsaKey; public RSAOAEPKeyExchangeDeformatter() { } - public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key) + public RSAOAEPKeyExchangeDeformatter(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } @@ -30,11 +27,8 @@ public override byte[] DecryptKeyExchange(byte[] rgbData) return _rsaKey.Decrypt(rgbData, RSAEncryptionPadding.OaepSHA1); } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 dd8568c359453d..2026b7766ae80d 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,11 +10,8 @@ public class RSAOAEPKeyExchangeFormatter : AsymmetricKeyExchangeFormatter private RandomNumberGenerator? RngValue; public RSAOAEPKeyExchangeFormatter() { } - public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key) + public RSAOAEPKeyExchangeFormatter(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } @@ -53,11 +50,8 @@ public RandomNumberGenerator? Rng set { RngValue = value; } } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 1ef165c992e8ee..30891570cf0459 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,10 +65,8 @@ public RSAOpenSsl(IntPtr handle) [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [UnsupportedOSPlatform("windows")] - public RSAOpenSsl(SafeEvpPKeyHandle pkeyHandle) + public RSAOpenSsl(SafeEvpPKeyHandle pkeyHandle!!) { - if (pkeyHandle == null) - throw new ArgumentNullException(nameof(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 ea54291305abcf..f01cdf3cbcb85d 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,11 +12,8 @@ public class RSAPKCS1KeyExchangeDeformatter : AsymmetricKeyExchangeDeformatter public RSAPKCS1KeyExchangeDeformatter() { } - public RSAPKCS1KeyExchangeDeformatter(AsymmetricAlgorithm key) + public RSAPKCS1KeyExchangeDeformatter(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } @@ -40,11 +37,8 @@ public override byte[] DecryptKeyExchange(byte[] rgbIn) return _rsaKey.Decrypt(rgbIn, RSAEncryptionPadding.Pkcs1); } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 b9cd034075a406..58b439942a24cc 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,11 +12,8 @@ public class RSAPKCS1KeyExchangeFormatter : AsymmetricKeyExchangeFormatter public RSAPKCS1KeyExchangeFormatter() { } - public RSAPKCS1KeyExchangeFormatter(AsymmetricAlgorithm key) + public RSAPKCS1KeyExchangeFormatter(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } @@ -34,11 +31,8 @@ public RandomNumberGenerator? Rng set { RngValue = value; } } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(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 22eeaae1fc6596..b3376f9b8ddc19 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,19 +13,13 @@ public class RSAPKCS1SignatureDeformatter : AsymmetricSignatureDeformatter private string? _algName; public RSAPKCS1SignatureDeformatter() { } - public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key) + public RSAPKCS1SignatureDeformatter(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } @@ -44,12 +38,8 @@ public override void SetHashAlgorithm(string strName) } } - public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) + public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(rgbHash)); - if (rgbSignature == null) - throw new ArgumentNullException(nameof(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 938e2a60c3eb20..af101c039ab964 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,19 +14,13 @@ public class RSAPKCS1SignatureFormatter : AsymmetricSignatureFormatter public RSAPKCS1SignatureFormatter() { } - public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key) + public RSAPKCS1SignatureFormatter(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } - public override void SetKey(AsymmetricAlgorithm key) + public override void SetKey(AsymmetricAlgorithm key!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - _rsaKey = (RSA)key; } @@ -45,10 +39,8 @@ public override void SetHashAlgorithm(string strName) } } - public override byte[] CreateSignature(byte[] rgbHash) + public override byte[] CreateSignature(byte[] rgbHash!!) { - if (rgbHash == null) - throw new ArgumentNullException(nameof(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 b299396c595d9a..b6d0c097b7913b 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,10 +163,8 @@ public static byte[] GetBytes(int count) return ret; } - internal void VerifyGetBytes(byte[] data, int offset, int count) + internal void VerifyGetBytes(byte[] data!!, int offset, int count) { - if (data == null) - throw new ArgumentNullException(nameof(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 e00508d66c237f..2bc9b39aa4dfcf 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,9 +26,8 @@ internal static unsafe void FillSpan(Span data) } } - public override void GetBytes(byte[] data) + public override void GetBytes(byte[] data!!) { - if (data == null) throw new ArgumentNullException(nameof(data)); GetBytes(new Span(data)); } @@ -46,9 +45,8 @@ public override unsafe void GetBytes(Span data) } } - public override void GetNonZeroBytes(byte[] data) + public override void GetNonZeroBytes(byte[] data!!) { - if (data == null) throw new ArgumentNullException(nameof(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 20190fd32fcd98..e5251f5c8b9bb2 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,17 +38,12 @@ public partial class Rfc2898DeriveBytes /// , and . /// public static byte[] Pbkdf2( - byte[] password, - byte[] salt, + byte[] password!!, + byte[] salt!!, int iterations, HashAlgorithmName hashAlgorithm, int outputLength) { - if (password is null) - throw new ArgumentNullException(nameof(password)); - if (salt is null) - throw new ArgumentNullException(nameof(salt)); - return Pbkdf2(new ReadOnlySpan(password), new ReadOnlySpan(salt), iterations, hashAlgorithm, outputLength); } @@ -162,17 +157,12 @@ public static void Pbkdf2( /// and use . /// public static byte[] Pbkdf2( - string password, - byte[] salt, + string password!!, + byte[] salt!!, int iterations, HashAlgorithmName hashAlgorithm, int outputLength) { - if (password is null) - throw new ArgumentNullException(nameof(password)); - if (salt is null) - throw new ArgumentNullException(nameof(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 9c0909109c5f8d..d06ebf51e53444 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 @@ -85,10 +85,8 @@ 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) { - if (salt is null) - throw new ArgumentNullException(nameof(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 684d69e9a228c4..d8623e523c2873 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,11 +47,8 @@ protected SHA1() /// /// is . /// - public static byte[] HashData(byte[] source) + public static byte[] HashData(byte[] source!!) { - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(source)); } @@ -133,10 +130,8 @@ 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)); @@ -157,10 +152,8 @@ 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)); @@ -182,10 +175,8 @@ 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)); @@ -216,12 +207,10 @@ public static ValueTask HashDataAsync(Stream source, CancellationToken c ///

/// 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 fb48e9ffe00319..fd8a03ca96fbf5 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,11 +46,8 @@ protected SHA256() /// /// is . /// - public static byte[] HashData(byte[] source) + public static byte[] HashData(byte[] source!!) { - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(source)); } @@ -133,10 +130,8 @@ 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)); @@ -157,10 +152,8 @@ 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)); @@ -182,10 +175,8 @@ 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)); @@ -216,12 +207,10 @@ public static ValueTask HashDataAsync(Stream source, CancellationToken c ///

/// 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 89ba9d5c78b85c..fa8618d50118d8 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,11 +46,8 @@ protected SHA384() /// /// is . /// - public static byte[] HashData(byte[] source) + public static byte[] HashData(byte[] source!!) { - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(source)); } @@ -132,10 +129,8 @@ 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)); @@ -156,10 +151,8 @@ 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)); @@ -181,10 +174,8 @@ 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)); @@ -215,12 +206,10 @@ public static ValueTask HashDataAsync(Stream source, CancellationToken c ///

/// 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 924af115013d97..6833478ca89e0b 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,11 +46,8 @@ protected SHA512() /// /// is . /// - public static byte[] HashData(byte[] source) + public static byte[] HashData(byte[] source!!) { - if (source is null) - throw new ArgumentNullException(nameof(source)); - return HashData(new ReadOnlySpan(source)); } @@ -132,10 +129,8 @@ 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)); @@ -156,10 +151,8 @@ 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)); @@ -181,10 +174,8 @@ 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)); @@ -215,12 +206,10 @@ public static ValueTask HashDataAsync(Stream source, CancellationToken c ///

/// 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 6415c9e5c03ae4..e50b658422a630 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,10 +16,8 @@ public SignatureDescription() { } - public SignatureDescription(SecurityElement el) + public SignatureDescription(SecurityElement el!!) { - if (el == null) - throw new ArgumentNullException(nameof(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 5e5cfa33a07b6a..b862304ea54dd7 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 @@ -447,12 +447,9 @@ 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) { // Padding mode is validated by callee. - if (ciphertext is null) - throw new ArgumentNullException(nameof(ciphertext)); - return DecryptEcb(new ReadOnlySpan(ciphertext), paddingMode); } @@ -566,12 +563,9 @@ 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) { // paddingMode is validated by callee - if (plaintext is null) - throw new ArgumentNullException(nameof(plaintext)); - return EncryptEcb(new ReadOnlySpan(plaintext), paddingMode); } @@ -690,13 +684,8 @@ 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) { - if (ciphertext is null) - throw new ArgumentNullException(nameof(ciphertext)); - if (iv is null) - throw new ArgumentNullException(nameof(iv)); - return DecryptCbc(new ReadOnlySpan(ciphertext), new ReadOnlySpan(iv), paddingMode); } @@ -847,13 +836,8 @@ 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) { - if (plaintext is null) - throw new ArgumentNullException(nameof(plaintext)); - if (iv is null) - throw new ArgumentNullException(nameof(iv)); - return EncryptCbc(new ReadOnlySpan(plaintext), new ReadOnlySpan(iv), paddingMode); } @@ -1021,13 +1005,8 @@ 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) { - if (ciphertext is null) - throw new ArgumentNullException(nameof(ciphertext)); - if (iv is null) - throw new ArgumentNullException(nameof(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 dfb681dc42519b..8add56937be4ba 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,13 +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) { // note: rgbIV is guaranteed to be cloned before this method, so no need to clone it again - if (rgbKey == null) - throw new ArgumentNullException(nameof(rgbKey)); - long keySize = rgbKey.Length * (long)BitsPerByte; if (keySize > int.MaxValue || !((int)keySize).IsLegalSize(LegalKeySizes)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); 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 1476cea2d57f47..ceaba8195a80c0 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,13 +8,10 @@ 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 { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - string oidValue = GetExpectedOidValue(); PublicKey publicKey = certificate.PublicKey; Oid algorithmOid = publicKey.Oid; @@ -45,13 +42,10 @@ internal static class CertificateExtensionsCommon } public static T? GetPrivateKey( - this X509Certificate2 certificate, + this X509Certificate2 certificate!!, Predicate? matchesConstraints = null) where T : AsymmetricAlgorithm { - if (certificate == null) - throw new ArgumentNullException(nameof(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 02061235b3935f..cf72e2f6239cbf 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,10 +58,8 @@ 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); @@ -85,10 +83,8 @@ public CertificateRequest(string subjectName, ECDsa key, HashAlgorithmName hashA /// /// 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; @@ -180,10 +176,8 @@ 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; @@ -244,11 +238,8 @@ public byte[] CreateSigningRequest() /// /// A with which to sign the request. /// - public byte[] CreateSigningRequest(X509SignatureGenerator signatureGenerator) + public byte[] CreateSigningRequest(X509SignatureGenerator signatureGenerator!!) { - if (signatureGenerator == null) - throw new ArgumentNullException(nameof(signatureGenerator)); - X501Attribute[] attributes = Array.Empty(); if (CertificateExtensions.Count > 0) @@ -414,13 +405,11 @@ public X509Certificate2 Create( /// which does not accept a value. /// public X509Certificate2 Create( - X509Certificate2 issuerCertificate, + X509Certificate2 issuerCertificate!!, DateTimeOffset notBefore, DateTimeOffset notAfter, ReadOnlySpan serialNumber) { - if (issuerCertificate == null) - throw new ArgumentNullException(nameof(issuerCertificate)); if (!issuerCertificate.HasPrivateKey) throw new ArgumentException(SR.Cryptography_CertReq_IssuerRequiresPrivateKey, nameof(issuerCertificate)); if (notAfter < notBefore) @@ -592,16 +581,12 @@ 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) { - if (issuerName == null) - throw new ArgumentNullException(nameof(issuerName)); - if (generator == null) - throw new ArgumentNullException(nameof(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/DSACertificateExtensions.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/DSACertificateExtensions.cs index ac63e7062228d0..62c0ca791c00ee 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,13 +30,8 @@ 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!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - if (privateKey == null) - throw new ArgumentNullException(nameof(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 8694dc25423a26..f41048bf494c91 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,13 +27,8 @@ 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!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - if (privateKey == null) - throw new ArgumentNullException(nameof(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 d62a967df7959c..15ec8ad9cae654 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,11 +214,8 @@ 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!!) { - if (keyValue == null) - throw new ArgumentNullException(nameof(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 ae14cc735a48f3..3d2667c7c335e9 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,15 +18,10 @@ internal sealed class Pkcs10CertificationRequestInfo internal Collection Attributes { get; } = new Collection(); internal Pkcs10CertificationRequestInfo( - X500DistinguishedName subject, - PublicKey publicKey, + X500DistinguishedName subject!!, + PublicKey publicKey!!, IEnumerable attributes) { - if (subject == null) - throw new ArgumentNullException(nameof(subject)); - if (publicKey == null) - throw new ArgumentNullException(nameof(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 da648c7c5edf9a..7ecc5f499c31a0 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,11 +14,8 @@ internal Pkcs9ExtensionRequest(IEnumerable extensions) { } - private static byte[] EncodeAttribute(IEnumerable extensions) + private static byte[] EncodeAttribute(IEnumerable extensions!!) { - if (extensions == null) - throw new ArgumentNullException(nameof(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 f88157eec37d4b..1aa566f2020d6e 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,13 +27,8 @@ 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!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - if (privateKey == null) - throw new ArgumentNullException(nameof(privateKey)); - if (certificate.HasPrivateKey) throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey); 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 099245168b6d1c..eb1e69c34ceedc 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,19 +33,13 @@ public void AddDnsName(string dnsName) AddGeneralName(new GeneralNameAsn { DnsName = s_idnMapping.GetAscii(dnsName) }); } - public void AddUri(Uri uri) + public void AddUri(Uri uri!!) { - if (uri == null) - throw new ArgumentNullException(nameof(uri)); - AddGeneralName(new GeneralNameAsn { Uri = uri.AbsoluteUri.ToString() }); } - public void AddIpAddress(IPAddress ipAddress) + public void AddIpAddress(IPAddress ipAddress!!) { - if (ipAddress == null) - throw new ArgumentNullException(nameof(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 0e8dc7efc9cab2..8ea61a2bcc00f9 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,10 +69,8 @@ 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) { - if (distinguishedName == null) - throw new ArgumentNullException(nameof(distinguishedName)); ThrowIfInvalid(flags); return X509Pal.Instance.X500DistinguishedNameEncode(distinguishedName, flags); 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 a17dbf0f21dd8a..6d9f3ad07d11ba 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,11 +156,8 @@ public X509Certificate(string fileName, SecureString? password) } [UnsupportedOSPlatform("browser")] - public X509Certificate(string fileName, string? password, X509KeyStorageFlags keyStorageFlags) + public X509Certificate(string fileName!!, string? password, X509KeyStorageFlags keyStorageFlags) { - if (fileName == null) - throw new ArgumentNullException(nameof(fileName)); - ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -169,11 +166,8 @@ public X509Certificate(string fileName, string? password, X509KeyStorageFlags ke } } - private protected X509Certificate(string fileName, ReadOnlySpan password, X509KeyStorageFlags keyStorageFlags) + private protected X509Certificate(string fileName!!, ReadOnlySpan password, X509KeyStorageFlags keyStorageFlags) { - if (fileName == null) - throw new ArgumentNullException(nameof(fileName)); - ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -185,12 +179,9 @@ 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 { - if (fileName == null) - throw new ArgumentNullException(nameof(fileName)); - ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -200,11 +191,8 @@ public X509Certificate(string fileName, SecureString? password, X509KeyStorageFl } [UnsupportedOSPlatform("browser")] - public X509Certificate(X509Certificate cert) + public X509Certificate(X509Certificate cert!!) { - if (cert == null) - throw new ArgumentNullException(nameof(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 0de268a2d60c1c..9bfe38e89d7487 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,11 +429,8 @@ public static X509ContentType GetCertContentType(ReadOnlySpan rawData) } [UnsupportedOSPlatform("browser")] - public static X509ContentType GetCertContentType(string fileName) + public static X509ContentType GetCertContentType(string fileName!!) { - if (fileName == null) - throw new ArgumentNullException(nameof(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); @@ -768,11 +765,8 @@ 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!!) { - if (privateKey is null) - throw new ArgumentNullException(nameof(privateKey)); - if (HasPrivateKey) throw new InvalidOperationException(SR.Cryptography_Cert_AlreadyHasPrivateKey); @@ -849,11 +843,8 @@ 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) { - if (certPemFilePath is null) - throw new ArgumentNullException(nameof(certPemFilePath)); - ReadOnlySpan certContents = File.ReadAllText(certPemFilePath); ReadOnlySpan keyContents = keyPemFilePath is null ? certContents : File.ReadAllText(keyPemFilePath); @@ -916,11 +907,8 @@ public static X509Certificate2 CreateFromPemFile(string certPemFilePath, string? /// /// [UnsupportedOSPlatform("browser")] - public static X509Certificate2 CreateFromEncryptedPemFile(string certPemFilePath, ReadOnlySpan password, string? keyPemFilePath = default) + public static X509Certificate2 CreateFromEncryptedPemFile(string certPemFilePath!!, ReadOnlySpan password, string? keyPemFilePath = default) { - if (certPemFilePath is null) - throw new ArgumentNullException(nameof(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 314715e3764603..50faccff83e9a7 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,19 +44,13 @@ public X509Certificate2Collection(X509Certificate2Collection certificates) } } - public int Add(X509Certificate2 certificate) + public int Add(X509Certificate2 certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - return base.Add(certificate); } - public void AddRange(X509Certificate2[] certificates) + public void AddRange(X509Certificate2[] certificates!!) { - if (certificates == null) - throw new ArgumentNullException(nameof(certificates)); - int i = 0; try { @@ -75,11 +69,8 @@ public void AddRange(X509Certificate2[] certificates) } } - public void AddRange(X509Certificate2Collection certificates) + public void AddRange(X509Certificate2Collection certificates!!) { - if (certificates == null) - throw new ArgumentNullException(nameof(certificates)); - int i = 0; try { @@ -121,11 +112,8 @@ public bool Contains(X509Certificate2 certificate) } } - public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly) + public X509Certificate2Collection Find(X509FindType findType, object findValue!!, bool validOnly) { - if (findValue == null) - throw new ArgumentNullException(nameof(findValue)); - return FindPal.FindFromCollection(this, findType, findValue, validOnly); } @@ -136,11 +124,8 @@ public X509Certificate2Collection Find(X509FindType findType, object findValue, IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public void Import(byte[] rawData) + public void Import(byte[] rawData!!) { - if (rawData == null) - throw new ArgumentNullException(nameof(rawData)); - Import(rawData.AsSpan()); } @@ -155,11 +140,8 @@ 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) { - if (rawData == null) - throw new ArgumentNullException(nameof(rawData)); - Import(rawData.AsSpan(), password.AsSpan(), keyStorageFlags); } @@ -211,11 +193,8 @@ 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) { - if (fileName == null) - throw new ArgumentNullException(nameof(fileName)); - X509Certificate.ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -237,11 +216,8 @@ public void Import(string fileName, string? password, X509KeyStorageFlags keySto /// /// 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) { - if (fileName == null) - throw new ArgumentNullException(nameof(fileName)); - X509Certificate.ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) @@ -251,27 +227,18 @@ public void Import(string fileName, ReadOnlySpan password, X509KeyStorageF } } - public void Insert(int index, X509Certificate2 certificate) + public void Insert(int index, X509Certificate2 certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - base.Insert(index, certificate); } - public void Remove(X509Certificate2 certificate) + public void Remove(X509Certificate2 certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - base.Remove(certificate); } - public void RemoveRange(X509Certificate2[] certificates) + public void RemoveRange(X509Certificate2[] certificates!!) { - if (certificates == null) - throw new ArgumentNullException(nameof(certificates)); - int i = 0; try { @@ -290,11 +257,8 @@ public void RemoveRange(X509Certificate2[] certificates) } } - public void RemoveRange(X509Certificate2Collection certificates) + public void RemoveRange(X509Certificate2Collection certificates!!) { - if (certificates == null) - throw new ArgumentNullException(nameof(certificates)); - int i = 0; try { @@ -338,11 +302,8 @@ public void RemoveRange(X509Certificate2Collection certificates) /// /// is . /// - public void ImportFromPemFile(string certPemFilePath) + public void ImportFromPemFile(string certPemFilePath!!) { - if (certPemFilePath is null) - throw new ArgumentNullException(nameof(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 0cca2b037b6c85..5fb2253feb520d 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 @@ -42,22 +42,16 @@ public int Add(X509Certificate value) return List.Add(value); } - public void AddRange(X509Certificate[] value) + public void AddRange(X509Certificate[] value!!) { - if (value == null) - throw new ArgumentNullException(nameof(value)); - for (int i = 0; i < value.Length; i++) { Add(value[i]); } } - public void AddRange(X509CertificateCollection value) + public void AddRange(X509CertificateCollection value!!) { - if (value == null) - throw new ArgumentNullException(nameof(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 2ee88458f8c7be..c99e74abd1d4fd 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,11 +11,8 @@ public class X509CertificateEnumerator : IEnumerator { private readonly IEnumerator _enumerator; - public X509CertificateEnumerator(X509CertificateCollection mappings) + public X509CertificateEnumerator(X509CertificateCollection mappings!!) { - if (mappings == null) - throw new ArgumentNullException(nameof(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 19f80241b0c897..b7a703b8f28d01 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,10 +55,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(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 5f7de6941e23e7..5e7b3b42f99bb1 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,10 +44,8 @@ public override void CopyFrom(AsnEncodedData asnEncodedData) _decoded = false; } - private static byte[] EncodeExtension(OidCollection enhancedKeyUsages) + private static byte[] EncodeExtension(OidCollection enhancedKeyUsages!!) { - if (enhancedKeyUsages == null) - throw new ArgumentNullException(nameof(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 617b42fd38c612..cd05abad2c5591 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 @@ -70,11 +70,8 @@ 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!!) { - if (asnEncodedData == null) - throw new ArgumentNullException(nameof(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 bbf1b300c8602b..d564b065fcb572 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,10 +62,8 @@ public X509Extension? this[string oid] } } - public int Add(X509Extension extension) + public int Add(X509Extension extension!!) { - if (extension == null) - throw new ArgumentNullException(nameof(extension)); _list.Add(extension); return _list.Count - 1; } @@ -75,10 +73,8 @@ 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) { - if (array == null) - throw new ArgumentNullException(nameof(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 b3fcc34330f11c..e74169e5aec1f5 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,18 +24,13 @@ 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!!) { - if (key == null) - throw new ArgumentNullException(nameof(key)); - return new ECDsaX509SignatureGenerator(key); } - public static X509SignatureGenerator CreateForRSA(RSA key, RSASignaturePadding signaturePadding) + public static X509SignatureGenerator CreateForRSA(RSA key!!, RSASignaturePadding signaturePadding) { - if (key == null) - throw new ArgumentNullException(nameof(key)); if (signaturePadding == null) throw new ArgumentNullException(nameof(signaturePadding)); 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 d97ead09424f14..076e88d8fdc25d 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,11 +126,8 @@ public bool IsOpen get { return _storePal != null; } } - public void Add(X509Certificate2 certificate) + public void Add(X509Certificate2 certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); @@ -140,11 +137,8 @@ public void Add(X509Certificate2 certificate) _storePal.Add(certificate.Pal); } - public void AddRange(X509Certificate2Collection certificates) + public void AddRange(X509Certificate2Collection certificates!!) { - if (certificates == null) - throw new ArgumentNullException(nameof(certificates)); - int i = 0; try { @@ -166,11 +160,8 @@ public void AddRange(X509Certificate2Collection certificates) } } - public void Remove(X509Certificate2 certificate) + public void Remove(X509Certificate2 certificate!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); - if (_storePal == null) throw new CryptographicException(SR.Cryptography_X509_StoreNotOpen); @@ -180,11 +171,8 @@ public void Remove(X509Certificate2 certificate) _storePal.Remove(certificate.Pal); } - public void RemoveRange(X509Certificate2Collection certificates) + public void RemoveRange(X509Certificate2Collection certificates!!) { - if (certificates == null) - throw new ArgumentNullException(nameof(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 1d239cf58fee57..3cf9b3d8f617db 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 @@ -73,20 +73,14 @@ private static byte[] EncodeExtension(ReadOnlySpan subjectKeyIdentifier) return X509Pal.Instance.EncodeX509SubjectKeyIdentifierExtension(subjectKeyIdentifier); } - private static byte[] EncodeExtension(string subjectKeyIdentifier) + private static byte[] EncodeExtension(string subjectKeyIdentifier!!) { - if (subjectKeyIdentifier == null) - throw new ArgumentNullException(nameof(subjectKeyIdentifier)); - byte[] subjectKeyIdentifiedBytes = subjectKeyIdentifier.LaxDecodeHexString(); return EncodeExtension(subjectKeyIdentifiedBytes); } - private static byte[] EncodeExtension(PublicKey key, X509SubjectKeyIdentifierHashAlgorithm algorithm) + private static byte[] EncodeExtension(PublicKey key!!, X509SubjectKeyIdentifierHashAlgorithm algorithm) { - if (key == null) - throw new ArgumentNullException(nameof(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 cb15f49730e263..465d7495881fe0 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,13 +12,8 @@ namespace System.Security.Cryptography { internal static class XmlKeyHelper { - internal static ParseState ParseDocument(string xmlString) + internal static ParseState ParseDocument(string xmlString!!) { - if (xmlString == null) - { - throw new ArgumentNullException(nameof(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 c9e0e7690389b4..64b4116e6f85c3 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,11 +268,8 @@ public SecurityElement ToXml() return root; } - public void FromXml(SecurityElement elem) + public void FromXml(SecurityElement elem!!) { - if (elem == 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 489f66d485e5ee..65c9347210206c 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,23 +66,13 @@ bool ICollection.IsReadOnly } } - public void Add(IdentityReference identity) + public void Add(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - _identities.Add(identity); } - public bool Remove(IdentityReference identity) + public bool Remove(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - if (Contains(identity)) { return _identities.Remove(identity); @@ -96,13 +86,8 @@ public void Clear() _identities.Clear(); } - public bool Contains(IdentityReference identity) + public bool Contains(IdentityReference identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(identity)); - } - return _identities.Contains(identity); } @@ -154,13 +139,8 @@ public IdentityReferenceCollection Translate(Type targetType) return Translate(targetType, false); } - public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess) + public IdentityReferenceCollection Translate(Type targetType!!, bool forceSuccess) { - if (targetType == null) - { - throw new ArgumentNullException(nameof(targetType)); - } - // // Target type must be a subclass of IdentityReference // @@ -394,12 +374,8 @@ internal sealed class IdentityReferenceEnumerator : IEnumerator(SafeAccessTokenHandle safeAccessTokenHandle, Func func) + public static T RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Func func!!) { - if (func == null) - throw new ArgumentNullException(nameof(func)); - T result = default!; RunImpersonatedInternal(safeAccessTokenHandle, () => result = func()); return result; @@ -922,12 +916,8 @@ private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle return safeLocalAllocHandle; } - private static string? GetAuthType(WindowsIdentity identity) + private static string? GetAuthType(WindowsIdentity identity!!) { - if (identity == null) - { - throw new ArgumentNullException(nameof(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 ea6011b3f443c1..5576ee858aceac 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,10 +29,10 @@ public class WindowsPrincipal : ClaimsPrincipal // Constructors. // - public WindowsPrincipal(WindowsIdentity ntIdentity) + public WindowsPrincipal(WindowsIdentity ntIdentity!!) : base(ntIdentity) { - _identity = ntIdentity ?? throw new ArgumentNullException(nameof(ntIdentity)); + _identity = ntIdentity; } // 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 3549abab1161a7..8e1b7892bdbc21 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 @@ -70,35 +70,20 @@ internal override TryParseDateTimeCallback GetDefaultDateTimeParser() protected Type FeedType { get; } - public override bool CanRead(XmlReader reader) + public override bool CanRead(XmlReader reader!!) { - if (reader == 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - ReadFeed(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer) + void IXmlSerializable.WriteXml(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - WriteFeed(writer); } @@ -112,13 +97,8 @@ public override void ReadFrom(XmlReader reader) ReadFeed(reader); } - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - writer.WriteStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace); WriteFeed(writer); writer.WriteEndElement(); @@ -493,33 +473,15 @@ internal void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseUri) protected override SyndicationFeed CreateFeedInstance() => CreateFeedInstance(FeedType); - protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed) + protected virtual SyndicationItem ReadItem(XmlReader reader!!, SyndicationFeed feed!!) { - if (feed == null) - { - throw new ArgumentNullException(nameof(feed)); - } - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - 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 (feed == null) - { - throw new ArgumentNullException(nameof(feed)); - } - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - 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 85494e557f1435..dae45443ecf0c5 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 @@ -62,35 +62,20 @@ public bool PreserveElementExtensions protected Type ItemType { get; } - public override bool CanRead(XmlReader reader) + public override bool CanRead(XmlReader reader!!) { - if (reader == 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - ReadItem(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer) + void IXmlSerializable.WriteXml(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - WriteItem(writer); } @@ -104,13 +89,8 @@ public override void ReadFrom(XmlReader reader) ReadItem(reader); } - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == 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 65720a8c7be0bf..8c120f4be97e79 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,34 +60,20 @@ public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite) public override string Version => App10Constants.Namespace; - public override bool CanRead(XmlReader reader) + public override bool CanRead(XmlReader reader!!) { - if (reader == 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - ReadDocument(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer) + void IXmlSerializable.WriteXml(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); @@ -96,12 +82,8 @@ void IXmlSerializable.WriteXml(XmlWriter writer) WriteDocument(writer); } - public override void ReadFrom(XmlReader reader) + public override void ReadFrom(XmlReader reader!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } if (!CanRead(reader)) { throw new XmlException(SR.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI)); @@ -110,12 +92,8 @@ public override void ReadFrom(XmlReader reader) ReadDocument(reader); } - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == 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 aec63b1949b0c9..b044ec5c71d1f9 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 @@ -45,34 +45,20 @@ 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 == 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - ReadDocument(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer) + void IXmlSerializable.WriteXml(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); @@ -81,13 +67,8 @@ void IXmlSerializable.WriteXml(XmlWriter writer) WriteDocument(writer); } - public override void ReadFrom(XmlReader reader) + public override void ReadFrom(XmlReader reader!!) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - reader.MoveToContent(); if (!CanRead(reader)) { @@ -97,12 +78,8 @@ public override void ReadFrom(XmlReader reader) ReadDocument(reader); } - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == 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 a2616f8f6ecb96..f0c4c72796b426 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,9 +15,9 @@ protected CategoriesDocumentFormatter() { } - protected CategoriesDocumentFormatter(CategoriesDocument documentToWrite) + protected CategoriesDocumentFormatter(CategoriesDocument documentToWrite!!) { - _document = documentToWrite ?? throw new ArgumentNullException(nameof(documentToWrite)); + _document = documentToWrite; } public CategoriesDocument Document => _document; 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 318b0014f45f5b..d31e5d5319b901 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,12 +63,8 @@ private static XmlBuffer CreateXmlBuffer(XmlDictionaryReader unparsedExtensionsR return buffer; } - internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) + internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions!!, int maxExtensionSize) { - if (readerOverUnparsedExtensions == null) - { - throw new ArgumentNullException(nameof(readerOverUnparsedExtensions)); - } if (maxExtensionSize < 0) { throw new ArgumentOutOfRangeException(nameof(maxExtensionSize)); @@ -84,13 +80,8 @@ internal void LoadElementExtensions(XmlBuffer buffer) _elementExtensions = new SyndicationElementExtensionCollection(buffer); } - internal void WriteAttributeExtensions(XmlWriter writer) + internal void WriteAttributeExtensions(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - if (_attributeExtensions != null) { foreach (XmlQualifiedName qname in _attributeExtensions.Keys) @@ -101,13 +92,8 @@ internal void WriteAttributeExtensions(XmlWriter writer) } } - internal void WriteElementExtensions(XmlWriter writer, Func shouldSkipElement = null) + internal void WriteElementExtensions(XmlWriter writer!!, Func shouldSkipElement = null) { - if (writer == 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 0bed469263e6a2..d20e5f50114f3a 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,23 +11,13 @@ public NullNotAllowedCollection() : base() { } - protected override void InsertItem(int index, TCollectionItem item) + protected override void InsertItem(int index, TCollectionItem item!!) { - if (item == 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 == 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 bc27065e93adfe..3112de805bf7dc 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,9 +9,9 @@ public ReferencedCategoriesDocument() { } - public ReferencedCategoriesDocument(Uri link) : base() + public ReferencedCategoriesDocument(Uri link!!) : base() { - Link = link ?? throw new ArgumentNullException(nameof(link)); + Link = link; } public Uri Link { get; set; } 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 d4bfc6e7f48e08..6bed1833f1311a 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,10 +31,10 @@ 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) { - Title = title ?? throw new ArgumentNullException(nameof(title)); - Link = link ?? throw new ArgumentNullException(nameof(link)); + Title = title; + Link = link; if (categories != null) { 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 eae365c0c67d29..c80af7a4f2d332 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 @@ -72,35 +72,20 @@ public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsA protected Type FeedType { get; } - public override bool CanRead(XmlReader reader) + public override bool CanRead(XmlReader reader!!) { - if (reader == 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - ReadFeed(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer) + void IXmlSerializable.WriteXml(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - WriteFeed(writer); } @@ -114,13 +99,8 @@ public override void ReadFrom(XmlReader reader) ReadFeed(reader); } - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - writer.WriteStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace); WriteFeed(writer); writer.WriteEndElement(); @@ -144,33 +124,15 @@ 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 (feed == null) - { - throw new ArgumentNullException(nameof(feed)); - } - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - 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 (feed == null) - { - throw new ArgumentNullException(nameof(feed)); - } - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } - 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 015315700ad0ae..cefccd9f561c82 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 @@ -85,35 +85,20 @@ public bool SerializeExtensionsAsAtom protected Type ItemType { get; } - public override bool CanRead(XmlReader reader) + public override bool CanRead(XmlReader reader!!) { - if (reader == 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - ReadItem(reader); } - void IXmlSerializable.WriteXml(XmlWriter writer) + void IXmlSerializable.WriteXml(XmlWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - WriteItem(writer); } @@ -127,13 +112,8 @@ public override void ReadFrom(XmlReader reader) ReadItem(reader); } - public override void WriteTo(XmlWriter writer) + public override void WriteTo(XmlWriter writer!!) { - if (writer == 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 495cd6f18f09e6..66319f9214a200 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,9 +16,9 @@ protected ServiceDocumentFormatter() { } - protected ServiceDocumentFormatter(ServiceDocument documentToWrite) + protected ServiceDocumentFormatter(ServiceDocument documentToWrite!!) { - _document = documentToWrite ?? throw new ArgumentNullException(nameof(documentToWrite)); + _document = documentToWrite; } public ServiceDocument Document => _document; @@ -53,34 +53,19 @@ 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 == 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 == null) - { - throw new ArgumentNullException(nameof(inlineCategories)); - } - return inlineCategories.CreateCategory(); } - protected static ResourceCollectionInfo CreateCollection(Workspace workspace) + protected static ResourceCollectionInfo CreateCollection(Workspace workspace!!) { - if (workspace == null) - { - throw new ArgumentNullException(nameof(workspace)); - } - return workspace.CreateResourceCollection(); } @@ -94,213 +79,108 @@ protected static ReferencedCategoriesDocument CreateReferencedCategories(Resourc return collection.CreateReferencedCategoriesDocument(); } - protected static Workspace CreateWorkspace(ServiceDocument document) + protected static Workspace CreateWorkspace(ServiceDocument document!!) { - if (document == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 f3df2e2b9e497b..0a25117ee8203e 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,13 +26,8 @@ public SyndicationCategory(string name, string scheme, string label) Label = label; } - protected SyndicationCategory(SyndicationCategory source) + protected SyndicationCategory(SyndicationCategory source!!) { - if (source == 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 52e281bf79a704..41d588b56e3f7c 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,12 +67,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(writer)); - } if (string.IsNullOrEmpty(outerElementName)) { throw new ArgumentException(SR.OuterElementNameNotSpecified, nameof(outerElementName)); @@ -96,13 +92,8 @@ public void WriteTo(XmlWriter writer, string outerElementName, string outerEleme writer.WriteEndElement(); } - internal void CopyAttributeExtensions(SyndicationContent source) + internal void CopyAttributeExtensions(SyndicationContent source!!) { - if (source == 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 fc3822a860a50a..32c1855a92a1ac 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,13 +19,8 @@ public class SyndicationElementExtension private string _outerName; private string _outerNamespace; - public SyndicationElementExtension(XmlReader xmlReader) + public SyndicationElementExtension(XmlReader xmlReader!!) { - if (xmlReader == null) - { - throw new ArgumentNullException(nameof(xmlReader)); - } - SyndicationFeedFormatter.MoveToStartElement(xmlReader); _outerName = xmlReader.LocalName; _outerNamespace = xmlReader.NamespaceURI; @@ -55,12 +50,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(dataContractExtension)); - } if (outerName == string.Empty) { throw new ArgumentException(SR.OuterNameOfElementExtensionEmpty, nameof(outerName)); @@ -76,13 +67,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(xmlSerializerExtension)); - } - if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); @@ -127,13 +113,8 @@ public string OuterNamespace public TExtension GetObject() => GetObject(new DataContractSerializer(typeof(TExtension))); - public TExtension GetObject(XmlObjectSerializer serializer) + public TExtension GetObject(XmlObjectSerializer serializer!!) { - if (serializer == null) - { - throw new ArgumentNullException(nameof(serializer)); - } - if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; @@ -144,13 +125,8 @@ public TExtension GetObject(XmlObjectSerializer serializer) } } - public TExtension GetObject(XmlSerializer serializer) + public TExtension GetObject(XmlSerializer serializer!!) { - if (serializer == null) - { - throw new ArgumentNullException(nameof(serializer)); - } - if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType())) { return (TExtension)_extensionData; @@ -179,13 +155,8 @@ public XmlReader GetReader() return reader; } - public void WriteTo(XmlWriter writer) + public void WriteTo(XmlWriter writer!!) { - if (writer == 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 49cf23de699ef2..e99e7386b1e745 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,13 +61,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(dataContractExtension)); - } - if (dataContractSerializer == null) { dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType()); @@ -75,13 +70,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(xmlSerializerExtension)); - } - if (serializer == null) { serializer = new XmlSerializer(xmlSerializerExtension.GetType()); @@ -89,13 +79,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(xmlReader)); - } - base.Add(new SyndicationElementExtension(xmlReader)); } @@ -112,23 +97,13 @@ 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 == 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 == null) - { - throw new ArgumentNullException(nameof(serializer)); - } - return ReadExtensions(extensionName, extensionNamespace, null, serializer); } @@ -168,13 +143,8 @@ protected override void ClearItems() _buffer = null; } - protected override void InsertItem(int index, SyndicationElementExtension item) + protected override void InsertItem(int index, SyndicationElementExtension item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - base.InsertItem(index, item); // clear the cached buffer if the operation is happening outside the constructor if (_initialized) @@ -191,13 +161,8 @@ 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 == 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 2ba333b92c9173..0a8391f8916c64 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,13 +67,8 @@ public SyndicationFeed(string title, string description, Uri feedAlternateLink, _items = items; } - protected SyndicationFeed(SyndicationFeed source, bool cloneItems) + protected SyndicationFeed(SyndicationFeed source!!, bool cloneItems) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); _contributors = FeedUtils.ClonePersons(source._contributors); @@ -409,13 +404,8 @@ 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 == 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 f4dbc2eb004f0c..019f0007b1f736 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,9 +22,9 @@ protected SyndicationFeedFormatter() DateTimeParser = GetDefaultDateTimeParser(); } - protected SyndicationFeedFormatter(SyndicationFeed feedToWrite) + protected SyndicationFeedFormatter(SyndicationFeed feedToWrite!!) { - _feed = feedToWrite ?? throw new ArgumentNullException(nameof(feedToWrite)); + _feed = feedToWrite; DateTimeParser = GetDefaultDateTimeParser(); } @@ -53,133 +53,68 @@ 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == null) - { - throw new ArgumentNullException(nameof(feed)); - } - if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -187,13 +122,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(item)); - } - if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -201,13 +131,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(category)); - } - if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -215,13 +140,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(link)); - } - if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -229,13 +149,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(person)); - } - if (FeedUtils.IsXmlns(name, ns)) { return true; @@ -248,159 +163,84 @@ 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == 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 == null) - { - throw new ArgumentNullException(nameof(person)); - } - person.WriteElementExtensions(writer, version); } - protected internal virtual void SetFeed(SyndicationFeed feed) + protected internal virtual void SetFeed(SyndicationFeed feed!!) { - _feed = feed ?? throw new ArgumentNullException(nameof(feed)); + _feed = feed; } internal Uri UriFromString(string uriString, UriKind uriKind, string localName, string namespaceURI, XmlReader reader) @@ -499,13 +339,8 @@ 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 == 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 4370ec9d8df246..24fea9ea0b6d0f 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,13 +48,8 @@ public SyndicationItem(string title, SyndicationContent content, Uri itemAlterna _lastUpdatedTime = lastUpdatedTime; } - protected SyndicationItem(SyndicationItem source) + protected SyndicationItem(SyndicationItem source!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - _extensions = source._extensions.Clone(); _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); @@ -155,13 +150,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - Atom10ItemFormatter atomSerializer = new Atom10ItemFormatter(); if (atomSerializer.CanRead(reader)) { 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 943f9b6e2ce399..9c7e95760c3a0c 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,9 +16,9 @@ protected SyndicationItemFormatter() _item = null; } - protected SyndicationItemFormatter(SyndicationItem itemToWrite) + protected SyndicationItemFormatter(SyndicationItem itemToWrite!!) { - _item = itemToWrite ?? throw new ArgumentNullException(nameof(itemToWrite)); + _item = itemToWrite; } public SyndicationItem Item => _item; @@ -33,9 +33,9 @@ protected SyndicationItemFormatter(SyndicationItem itemToWrite) public abstract void WriteTo(XmlWriter writer); - protected internal virtual void SetItem(SyndicationItem item) + protected internal virtual void SetItem(SyndicationItem item!!) { - _item = item ?? throw new ArgumentNullException(nameof(item)); + _item = item; } internal static SyndicationItem CreateItemInstance(Type itemType) 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 b9fc1f4ce7c513..62ffbafd572201 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,13 +35,8 @@ public SyndicationLink() : this(null, null, null, null, 0) { } - protected SyndicationLink(SyndicationLink source) + protected SyndicationLink(SyndicationLink source!!) { - if (source == 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 5239fd9d55a01f..6c4750aa163f1d 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,13 +27,8 @@ public SyndicationPerson(string email, string name, string uri) Uri = uri; } - protected SyndicationPerson(SyndicationPerson source) + protected SyndicationPerson(SyndicationPerson source!!) { - if (source == 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 a8527be8e514ac..19b2a8012b4c32 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,9 +11,9 @@ public class UrlSyndicationContent : SyndicationContent { private readonly string _mediaType; - public UrlSyndicationContent(Uri url, string mediaType) : base() + public UrlSyndicationContent(Uri url!!, string mediaType) : base() { - Url = url ?? 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 a4f5139a95dd48..b8427a6b642069 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,13 +17,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(reader)); - } - SyndicationFeedFormatter.MoveToStartElement(reader); if (reader.HasAttributes) { @@ -65,10 +60,10 @@ public XmlSyndicationContent(string type, object xmlSerializerExtension, XmlSeri Extension = new SyndicationElementExtension(xmlSerializerExtension, serializer); } - public XmlSyndicationContent(string type, SyndicationElementExtension extension) + public XmlSyndicationContent(string type, SyndicationElementExtension extension!!) { _type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type; - Extension = extension ?? throw new ArgumentNullException(nameof(extension)); + Extension = extension; } protected XmlSyndicationContent(XmlSyndicationContent source) : base(source) @@ -138,13 +133,8 @@ 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 == 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 51c83257ce9d06..9d78898292a904 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -862,11 +862,8 @@ public void Start() /// /// Starts a service in the machine specified. /// - public void Start(string[] args) + public void Start(string[] args!!) { - if (args == null) - throw new ArgumentNullException(nameof(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 461212e622b67a..0d06bd42d072de 100644 --- a/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs +++ b/src/libraries/System.Speech/src/Internal/ObjectToken/ObjectToken.cs @@ -15,14 +15,9 @@ internal class ObjectToken : RegistryDataKey, ISpObjectToken { #region Constructors - protected ObjectToken(ISpObjectToken sapiObjectToken, bool disposeSapiToken) + protected ObjectToken(ISpObjectToken sapiObjectToken!!, bool disposeSapiToken) : base(sapiObjectToken) { - if (sapiObjectToken == null) - { - throw new ArgumentNullException(nameof(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 ee3c74beebcaa4..bed2dfe68d6d42 100644 --- a/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs +++ b/src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsRulesCollection.cs @@ -22,12 +22,8 @@ public void Add(params SrgsRule[] rules) base.Add(rules[iRule]); } } - protected override string GetKeyForItem(SrgsRule rule) + protected override string GetKeyForItem(SrgsRule rule!!) { - if (rule == null) - { - throw new ArgumentNullException(nameof(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 e845b6079db4b2..189a16cf8c3007 100644 --- a/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs +++ b/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs @@ -16,13 +16,8 @@ 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) { - if (lexicalForm == null) - { - throw new ArgumentNullException(nameof(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/EncodingNLS.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncodingNLS.cs index c2681e3a4d2e68..2923bd2a9dc899 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 @@ -69,12 +69,8 @@ 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!!) { - // Validate input - if (s == null) - throw new ArgumentNullException(nameof(s)); - fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } 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 50666e57a8f721..c3faf767ee5db1 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,13 +14,8 @@ internal sealed class DefaultHtmlEncoder : HtmlEncoder private readonly OptimizedInboxTextEncoder _innerEncoder; - internal DefaultHtmlEncoder(TextEncoderSettings settings) + internal DefaultHtmlEncoder(TextEncoderSettings settings!!) { - if (settings is null) - { - throw new ArgumentNullException(nameof(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 7b23363e2e2063..e7a003ddb38da2 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,13 +18,8 @@ internal DefaultJavaScriptEncoder(TextEncoderSettings settings) { } - private DefaultJavaScriptEncoder(TextEncoderSettings settings, bool allowMinimalJsonEscaping) + private DefaultJavaScriptEncoder(TextEncoderSettings settings!!, bool allowMinimalJsonEscaping) { - if (settings is null) - { - throw new ArgumentNullException(nameof(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 95f444c56368a6..671ec2f80fb472 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,13 +12,8 @@ internal sealed class DefaultUrlEncoder : UrlEncoder private readonly OptimizedInboxTextEncoder _innerEncoder; - internal DefaultUrlEncoder(TextEncoderSettings settings) + internal DefaultUrlEncoder(TextEncoderSettings settings!!) { - if (settings is null) - { - throw new ArgumentNullException(nameof(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 a7142b188cb02d..bfa37ddb9db8dc 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 @@ -201,16 +201,8 @@ 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 (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } ValidateRanges(startIndex, characterCount, actualInputLength: value.Length); int indexOfFirstCharToEncode = FindFirstCharacterToEncode(value.AsSpan(startIndex, characterCount)); @@ -235,16 +227,8 @@ public virtual void Encode(TextWriter output, string value, int startIndex, int /// 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 (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } 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 d02c04c3ceb8a2..e2013826b7b2c6 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,13 +24,8 @@ public TextEncoderSettings() /// /// Instantiates the filter by cloning the allow list of another . /// - public TextEncoderSettings(TextEncoderSettings other) + public TextEncoderSettings(TextEncoderSettings other!!) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - _allowedCodePointsBitmap = other.GetAllowedCodePointsBitmap(); // copy byval } @@ -38,12 +33,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(allowedRanges)); - } AllowRanges(allowedRanges); } @@ -58,13 +49,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(characters)); - } - for (int i = 0; i < characters.Length; i++) { _allowedCodePointsBitmap.AllowChar(characters[i]); @@ -74,13 +60,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(codePoints)); - } - foreach (var allowedCodePoint in codePoints) { // If the code point can't be represented as a BMP character, skip it. @@ -94,13 +75,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(range)); - } - int firstCodePoint = range.FirstCodePoint; int rangeSize = range.Length; for (int i = 0; i < rangeSize; i++) @@ -114,13 +90,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(ranges)); - } - for (int i = 0; i < ranges.Length; i++) { AllowRange(ranges[i]); @@ -146,13 +117,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(characters)); - } - for (int i = 0; i < characters.Length; i++) { _allowedCodePointsBitmap.ForbidChar(characters[i]); @@ -162,13 +128,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(range)); - } - int firstCodePoint = range.FirstCodePoint; int rangeSize = range.Length; for (int i = 0; i < rangeSize; i++) @@ -182,13 +143,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(ranges)); - } - for (int i = 0; i < ranges.Length; i++) { ForbidRange(ranges[i]); 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 6ceaa0af7dd950..2a06c78204e9f5 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,13 +115,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - ArraySegment drained = ReadToEnd(utf8Json); Debug.Assert(drained.Array != null); try @@ -196,15 +191,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - return ParseAsyncCore(utf8Json, options, cancellationToken); } @@ -311,13 +301,8 @@ 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 == null) - { - throw new ArgumentNullException(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 33f4f33b46c510..6a2e6b88fc785c 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,13 +103,8 @@ public void Dispose() /// /// The parent has been disposed. /// - public void WriteTo(Utf8JsonWriter writer) + public void WriteTo(Utf8JsonWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(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 63963db4b5fd1a..c4a4613203e5b9 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,11 +111,8 @@ public int GetArrayLength() /// /// The parent has been disposed. /// - public JsonElement GetProperty(string propertyName) + public JsonElement GetProperty(string propertyName!!) { - if (propertyName == null) - throw new ArgumentNullException(nameof(propertyName)); - if (TryGetProperty(propertyName, out JsonElement property)) { return property; @@ -232,11 +229,8 @@ 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 == null) - throw new ArgumentNullException(nameof(propertyName)); - return TryGetProperty(propertyName.AsSpan(), out value); } @@ -1300,13 +1294,8 @@ internal bool TextEqualsHelper(ReadOnlySpan text, bool isPropertyName) /// /// The parent has been disposed. /// - public void WriteTo(Utf8JsonWriter writer) + public void WriteTo(Utf8JsonWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(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 9a5d58086abb3d..f22ce88dd6f853 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,13 +110,8 @@ internal bool EscapedNameEquals(ReadOnlySpan utf8Text) /// /// The parent has been disposed. /// > - public void WriteTo(Utf8JsonWriter writer) + public void WriteTo(Utf8JsonWriter writer!!) { - if (writer == null) - { - throw new ArgumentNullException(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 8b10b39eda0148..ca71e316b8f34e 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,11 +43,8 @@ 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 == null) - throw new ArgumentNullException(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 686fee2afec1e1..a77087025deec5 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 @@ -83,13 +83,8 @@ public void Clear() _propertyDictionary?.Clear(); } - public bool ContainsKey(string propertyName) + public bool ContainsKey(string propertyName!!) { - if (propertyName == null) - { - throw new ArgumentNullException(nameof(propertyName)); - } - return ContainsProperty(propertyName); } @@ -159,13 +154,8 @@ 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 == null) - { - throw new ArgumentNullException(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 c420a7eec5f371..ba03c8bb9b874c 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 @@ -152,13 +152,8 @@ 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 == null) - { - throw new ArgumentNullException(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 0d6f3a75263ebf..4087ec2323f863 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 @@ -66,15 +66,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(json)); - } - JsonElement element = JsonElement.ParseValue(json, documentOptions); return JsonNodeConverter.Create(element, nodeOptions); } @@ -114,15 +109,10 @@ 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 == null) - { - throw new ArgumentNullException(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 ad439d17822509..99ceb26c35c8d8 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 @@ -113,13 +113,8 @@ public int Count /// /// is . /// - public bool Remove(string propertyName) + public bool Remove(string propertyName!!) { - if (propertyName == null) - { - throw new ArgumentNullException(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 04a64c3e44ef4d..b380950c3fda87 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 @@ -82,13 +82,8 @@ 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 == null) - { - throw new ArgumentNullException(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 87b6953f46765b..3a2407c68f5354 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 @@ -61,13 +61,8 @@ 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 == null) - { - throw new ArgumentNullException(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 df596feb79a9d0..45084fefdc59ce 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 @@ -15,13 +15,8 @@ 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 == null) - { - throw new ArgumentNullException(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 35d010afd18bd2..13759e456d045f 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 @@ -25,13 +25,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(writer)); - } - if (_converter != null) { options ??= JsonSerializerOptions.Default; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConverterList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConverterList.cs index 58102d827e544f..dac1920eb1ca2c 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConverterList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ConverterList.cs @@ -47,13 +47,8 @@ public JsonConverter this[int index] public bool IsReadOnly => false; - public void Add(JsonConverter item) + public void Add(JsonConverter item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - _options.VerifyMutable(); _list.Add(item); } @@ -84,13 +79,8 @@ public int IndexOf(JsonConverter item) return _list.IndexOf(item); } - public void Insert(int index, JsonConverter item) + public void Insert(int index, JsonConverter item!!) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - _options.VerifyMutable(); _list.Insert(index, 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 5ee913f18d9482..2596023f6b0dd8 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 @@ -41,9 +41,9 @@ internal JsonConverter Converter internal override bool ConstructorIsParameterized => Converter.ConstructorIsParameterized; - public JsonMetadataServicesConverter(Func> converterCreator, ConverterStrategy converterStrategy) + public JsonMetadataServicesConverter(Func> converterCreator!!, ConverterStrategy converterStrategy) { - _converterCreator = converterCreator ?? throw new ArgumentNullException(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 ccf639bdec1793..2036aaaae3f95d 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,13 +10,9 @@ 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!!) { // Bridge from resumable to value converters. - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } ReadStack state = default; state.Initialize(typeToConvert, options, supportContinuation: false); @@ -24,13 +20,9 @@ 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!!) { // Bridge from resumable to value converters. - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } WriteStack state = default; state.Initialize(typeof(T), options, supportContinuation: false); 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 57a40db9afb9b3..d43f34223f241d 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 @@ -27,13 +27,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(document)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadDocument(document, jsonTypeInfo); } @@ -56,13 +51,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(document)); - } - if (returnType == null) { throw new ArgumentNullException(nameof(returnType)); @@ -93,18 +83,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(document)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadDocument(document, jsonTypeInfo); } @@ -144,23 +124,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(document)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(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 91f49589f457db..a92df30d47a9c3 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 @@ -76,13 +76,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadUsingMetadata(element, jsonTypeInfo); } @@ -118,18 +113,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(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 aa9675773d3b0d..0fdd7fab13e57c 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 @@ -75,13 +75,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadNode(node, jsonTypeInfo); } @@ -117,18 +112,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(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 50142fb4697f6e..a4ccb4ad4ac343 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 @@ -79,13 +79,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadFromSpan(utf8Json, jsonTypeInfo); } @@ -112,18 +107,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(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 0fd54b59100513..46963245c89af2 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,15 +42,10 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask DeserializeAsync( - Stream utf8Json, + Stream utf8Json!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadAllAsync(utf8Json, jsonTypeInfo, cancellationToken); } @@ -77,14 +72,9 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static TValue? Deserialize( - Stream utf8Json, + Stream utf8Json!!, JsonSerializerOptions? options = null) { - if (utf8Json == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - return ReadAllUsingOptions(utf8Json, typeof(TValue), options); } @@ -113,21 +103,11 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAllAsync(utf8Json, jsonTypeInfo, cancellationToken); } @@ -154,20 +134,10 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static object? Deserialize( - Stream utf8Json, - Type returnType, + Stream utf8Json!!, + Type returnType!!, JsonSerializerOptions? options = null) { - if (utf8Json == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - return ReadAllUsingOptions(utf8Json, returnType, options); } @@ -195,20 +165,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadAllAsync(utf8Json, jsonTypeInfo, cancellationToken); } @@ -233,19 +193,9 @@ public static partial class JsonSerializer /// for or its serializable members. /// public static TValue? Deserialize( - Stream utf8Json, - JsonTypeInfo jsonTypeInfo) + Stream utf8Json!!, + JsonTypeInfo jsonTypeInfo!!) { - if (utf8Json == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadAll(utf8Json, jsonTypeInfo); } @@ -277,26 +227,11 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - return ReadAllAsync(utf8Json, GetTypeInfo(context, returnType), cancellationToken); } @@ -325,25 +260,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - return ReadAll(utf8Json, GetTypeInfo(context, returnType)); } @@ -362,15 +282,10 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static IAsyncEnumerable DeserializeAsyncEnumerable( - Stream utf8Json, + Stream utf8Json!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { - if (utf8Json == null) - { - throw new ArgumentNullException(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 9056413479aca0..edf1f421d08c90 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,13 +42,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(json)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadFromSpan(json.AsSpan(), jsonTypeInfo); } @@ -114,18 +109,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(json)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpan(json.AsSpan(), jsonTypeInfo)!; } @@ -158,15 +143,10 @@ 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) { // default/null span is treated as empty - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadFromSpan(json, jsonTypeInfo)!; } @@ -202,20 +182,8 @@ 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!!) { - // default/null span is treated as empty - - if (json == null) - { - throw new ArgumentNullException(nameof(json)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadFromSpan(json.AsSpan(), jsonTypeInfo); } @@ -250,15 +218,8 @@ 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!!) { - // default/null span is treated as empty - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return ReadFromSpan(json, jsonTypeInfo); } @@ -297,23 +258,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(json)); - } - - if (returnType == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, returnType); return ReadFromSpan(json.AsSpan(), jsonTypeInfo); } @@ -353,18 +299,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(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 8bc8bf3818bb08..8e8641f027d7cd 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 @@ -161,13 +161,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return Read(ref reader, jsonTypeInfo); } @@ -220,18 +215,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(returnType)); - } - - if (context == null) - { - throw new ArgumentNullException(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 5e7bd64a797e3c..aa280ec24cf166 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,13 +70,8 @@ public static byte[] SerializeToUtf8Bytes( /// /// is . /// - public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo jsonTypeInfo) + public static byte[] SerializeToUtf8Bytes(TValue value, JsonTypeInfo jsonTypeInfo!!) { - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return WriteBytesUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -101,13 +96,8 @@ 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 == null) - { - throw new ArgumentNullException(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 ec4db4ff708fe0..cbf552e87bb186 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 @@ -68,13 +68,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return WriteDocumentUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -96,13 +91,8 @@ 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 == null) - { - throw new ArgumentNullException(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 f28b67bcfe29f7..b70d18a46cc40a 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 @@ -68,13 +68,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return WriteElementUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -96,13 +91,8 @@ 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 == null) - { - throw new ArgumentNullException(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 761798f14d921d..415f1417ae6071 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 @@ -96,13 +96,8 @@ 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) - { - throw new ArgumentNullException(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 98ae1c6b1ee515..4592c3bcdacab7 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 @@ -69,13 +69,8 @@ public static partial class JsonSerializer /// /// is . /// - public static JsonNode? SerializeToNode(TValue value, JsonTypeInfo jsonTypeInfo) + public static JsonNode? SerializeToNode(TValue value, JsonTypeInfo jsonTypeInfo!!) { - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return WriteNodeUsingGeneratedSerializer(value, jsonTypeInfo); } @@ -97,13 +92,8 @@ 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 == null) - { - throw new ArgumentNullException(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 50722caeb3a9ac..bc71fa13dec703 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,16 +39,11 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - Type runtimeType = GetRuntimeType(value); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); return WriteStreamAsync(utf8Json, value!, jsonTypeInfo, cancellationToken); @@ -70,15 +65,10 @@ public static Task SerializeAsync( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Stream utf8Json, + Stream utf8Json!!, TValue value, JsonSerializerOptions? options = null) { - if (utf8Json == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - Type runtimeType = GetRuntimeType(value); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteStream(utf8Json, value!, jsonTypeInfo); @@ -105,17 +95,12 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); return WriteStreamAsync(utf8Json, value!, jsonTypeInfo, cancellationToken); @@ -140,16 +125,11 @@ public static Task SerializeAsync( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Stream utf8Json, + Stream utf8Json!!, object? value, Type inputType, JsonSerializerOptions? options = null) { - if (utf8Json == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteStream(utf8Json, value!, jsonTypeInfo); @@ -172,21 +152,11 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - return WriteStreamAsync(utf8Json, value, jsonTypeInfo, cancellationToken); } @@ -205,20 +175,10 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - WriteStream(utf8Json, value, jsonTypeInfo); } @@ -242,22 +202,12 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); return WriteStreamAsync( utf8Json, @@ -284,21 +234,11 @@ 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 == null) - { - throw new ArgumentNullException(nameof(utf8Json)); - } - - if (context == null) - { - throw new ArgumentNullException(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 cb5a5055ac512a..7e24645a4e8c04 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,25 +109,15 @@ 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 == null) - { - throw new ArgumentNullException(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 == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - JsonSerializerOptions options = jsonTypeInfo.Options; using (var output = new PooledByteBufferWriter(options.DefaultBufferSize)) @@ -141,13 +131,8 @@ 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 == null) - { - throw new ArgumentNullException(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 94be4809a78b3c..526969f3c0df56 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,15 +25,10 @@ public static partial class JsonSerializer /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Utf8JsonWriter writer, + Utf8JsonWriter writer!!, TValue value, JsonSerializerOptions? options = null) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - Type runtimeType = GetRuntimeType(value); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteUsingSerializer(writer, value, jsonTypeInfo); @@ -58,16 +53,11 @@ public static void Serialize( /// [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static void Serialize( - Utf8JsonWriter writer, + Utf8JsonWriter writer!!, object? value, Type inputType, JsonSerializerOptions? options = null) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - Type runtimeType = GetRuntimeTypeAndValidateInputType(value, inputType); JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, runtimeType); WriteUsingSerializer(writer, value, jsonTypeInfo); @@ -87,18 +77,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (jsonTypeInfo == null) - { - throw new ArgumentNullException(nameof(jsonTypeInfo)); - } - WriteUsingGeneratedSerializer(writer, value, jsonTypeInfo); } @@ -123,18 +103,8 @@ public static void Serialize(Utf8JsonWriter writer, TValue value, JsonTy /// 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 == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (context == null) - { - throw new ArgumentNullException(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.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs index 9b280c2904a81f..fb5495a44c31ba 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 @@ -83,13 +83,8 @@ public JsonSerializerOptions() /// /// is . /// - public JsonSerializerOptions(JsonSerializerOptions options) + public JsonSerializerOptions(JsonSerializerOptions options!!) { - if (options == null) - { - throw new ArgumentNullException(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.Converters.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonMetadataServices.Converters.cs index e9173db256403b..f649e358507113 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 @@ -228,13 +228,8 @@ 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 == null) - { - throw new ArgumentNullException(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 14d002cf7cb1e6..89ff137ed74bff 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 @@ -20,18 +20,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - Type? declaringType = propertyInfo.DeclaringType; if (declaringType == null) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs index aea2e5a8e8c289..547173ba0f39e3 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs @@ -138,10 +138,10 @@ internal JsonTypeInfo() Debug.Assert(false, "This constructor should not be called."); } - internal JsonTypeInfo(Type type, JsonSerializerOptions options, bool dummy) + internal JsonTypeInfo(Type type, JsonSerializerOptions options!!, bool dummy) { Type = type; - Options = options ?? throw new ArgumentNullException(nameof(options)); + Options = options; // Setting this option is deferred to the initialization methods of the various metadada info types. PropertyInfoForTypeInfo = null!; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoInternalOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoInternalOfT.cs index 552b49658dddd2..6b7e9ed44f432a 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoInternalOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoInternalOfT.cs @@ -55,17 +55,12 @@ public JsonTypeInfoInternal(JsonSerializerOptions options, JsonObjectInfoValues< /// public JsonTypeInfoInternal( JsonSerializerOptions options, - JsonCollectionInfoValues collectionInfo, + JsonCollectionInfoValues collectionInfo!!, Func> converterCreator, object? createObjectWithArgs = null, object? addFunc = null) : base(typeof(T), options) { - if (collectionInfo == null) - { - throw new ArgumentNullException(nameof(collectionInfo)); - } - ConverterStrategy strategy = collectionInfo.KeyInfo == null ? ConverterStrategy.Enumerable : ConverterStrategy.Dictionary; JsonConverter converter = new JsonMetadataServicesConverter(converterCreator, strategy); 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 543afe1c89df71..9764b57c6fa696 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 @@ -478,13 +478,8 @@ 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 == null) - { - throw new ArgumentNullException(nameof(propertyName)); - } - if (value == null) { WriteNull(propertyName.AsSpan()); 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 9b22c33ac7d8f7..72f886ec489e19 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,9 +99,9 @@ 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) { - _output = bufferWriter ?? throw new ArgumentNullException(nameof(bufferWriter)); + _output = bufferWriter; _options = options; if (_options.MaxDepth == 0) @@ -120,10 +120,8 @@ public Utf8JsonWriter(IBufferWriter bufferWriter, JsonWriterOptions option /// /// 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 == null) - throw new ArgumentNullException(nameof(utf8Json)); if (!utf8Json.CanWrite) throw new ArgumentException(SR.StreamNotWritable); diff --git a/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.ParameterMatching.cs b/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.ParameterMatching.cs index 66f1c3c912d10f..6ad72300aba2d9 100644 --- a/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.ParameterMatching.cs +++ b/src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.ParameterMatching.cs @@ -1354,6 +1354,7 @@ public void StructWithPropertyInit_OverrideInitedProperty() public struct StructWithPropertyInit { + public StructWithPropertyInit() { B = 0; } public long A { get; set; } = 42; public long B { get; set; } } @@ -1369,6 +1370,7 @@ public void StructWithFieldInit_DeseralizeEmptyObject() public struct StructWithFieldInit { + public StructWithFieldInit() { A = 0; } public long A; public long B = 42; } 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 e344db40f5775b..675b417ef043b8 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/EventWaitHandleAcl.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/EventWaitHandleAcl.cs @@ -124,12 +124,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(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 b19a310315bd3f..87c14e40ad237c 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/MutexAcl.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/MutexAcl.cs @@ -115,12 +115,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(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 eee92069b3a7ff..35ee2c48942c57 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/SemaphoreAcl.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/SemaphoreAcl.cs @@ -128,12 +128,8 @@ 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) { - if (name == null) - { - throw new ArgumentNullException(nameof(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 252480a6e268e1..77c7732162cf63 100644 --- a/src/libraries/System.Threading.AccessControl/src/System/Threading/ThreadingAclExtensions.cs +++ b/src/libraries/System.Threading.AccessControl/src/System/Threading/ThreadingAclExtensions.cs @@ -16,11 +16,8 @@ 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!!) { - if (eventSecurity == null) - throw new ArgumentNullException(nameof(eventSecurity)); - eventSecurity.Persist(handle.GetSafeWaitHandle()); } @@ -29,11 +26,8 @@ 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!!) { - if (mutexSecurity == null) - throw new ArgumentNullException(nameof(mutexSecurity)); - mutexSecurity.Persist(mutex.GetSafeWaitHandle()); } @@ -42,11 +36,8 @@ 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!!) { - if (semaphoreSecurity == null) - throw new ArgumentNullException(nameof(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 156489276902cc..3c984e6927f2e8 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 @@ -52,13 +52,8 @@ 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 == 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 74ef7ec9e890b9..315ff5faf7bf24 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 @@ -31,9 +31,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 ?? throw new ArgumentNullException(nameof(options)); + _options = 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 acc8f1d58ad742..c39e3639a9011f 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 ?? throw new ArgumentNullException(nameof(name)); + _name = 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 6593d895a6810e..ac4de8ecbd7ce1 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 @@ -32,9 +32,9 @@ public sealed class TokenBucketRateLimiter : RateLimiter /// Initializes the . /// /// Options to specify the behavior of the . - public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options) + public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options!!) { - _options = options ?? throw new ArgumentNullException(nameof(options)); + _options = options; _tokenCount = options.TokenLimit; if (_options.AutoReplenishment) 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 972a5c939f02b5..d59b9e2d821054 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,23 +14,13 @@ 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 IAsyncEnumerable ReceiveAllAsync(this IReceivableSourceBlock source, CancellationToken cancellationToken = default) + public static async IAsyncEnumerable ReceiveAllAsync(this IReceivableSourceBlock source!!, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - if (source == null) + while (await source.OutputAvailableAsync(cancellationToken).ConfigureAwait(false)) { - throw new ArgumentNullException(nameof(source)); - } - - return ReceiveAllAsyncCore(source, cancellationToken); - - static async IAsyncEnumerable ReceiveAllAsyncCore(IReceivableSourceBlock source, [EnumeratorCancellation] CancellationToken cancellationToken) - { - while (await source.OutputAvailableAsync(cancellationToken).ConfigureAwait(false)) + while (source.TryReceive(out TOutput? item)) { - while (source.TryReceive(out TOutput? item)) - { - yield return 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 9cca871101592e..f196b8b631c52b 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs @@ -31,13 +31,9 @@ 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!!) { - // Validate arguments - if (source == null) throw new ArgumentNullException(nameof(source)); - if (target == 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); @@ -71,17 +67,11 @@ 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!!) { - // Validate arguments - if (source == null) throw new ArgumentNullException(nameof(source)); - if (target == null) throw new ArgumentNullException(nameof(target)); - if (linkOptions == null) throw new ArgumentNullException(nameof(linkOptions)); - if (predicate == 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); @@ -236,9 +226,8 @@ 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 == null) throw new ArgumentNullException(nameof(target)); return target.OfferMessage(Common.SingleMessageHeader, item, source: null, consumeToAccept: false) == DataflowMessageStatus.Accepted; } @@ -284,11 +273,8 @@ 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) { - // Validate arguments. No validation necessary for item. - if (target == null) throw new ArgumentNullException(nameof(target)); - // Fast path check for cancellation if (cancellationToken.IsCancellationRequested) return Common.CreateTaskFromCancellation(cancellationToken); @@ -761,10 +747,8 @@ 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 == null) throw new ArgumentNullException(nameof(source)); - return source.TryReceive(null, out item); } #endregion @@ -838,12 +822,9 @@ 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) { // Validate arguments - - - if (source == null) throw new ArgumentNullException(nameof(source)); if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); // Return the task representing the core receive operation @@ -921,10 +902,9 @@ 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) { // Validate arguments - if (source == null) throw new ArgumentNullException(nameof(source)); if (!Common.IsValidTimeout(timeout)) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); // Do fast path checks for both cancellation and data already existing. @@ -1397,11 +1377,8 @@ public static Task OutputAvailableAsync(this ISourceBlock public static Task OutputAvailableAsync( - this ISourceBlock source, CancellationToken cancellationToken) + this ISourceBlock source!!, CancellationToken cancellationToken) { - // Validate arguments - if (source == null) throw new ArgumentNullException(nameof(source)); - // Fast path for cancellation if (cancellationToken.IsCancellationRequested) return Common.CreateTaskFromCancellation(cancellationToken); @@ -1533,9 +1510,8 @@ void IDataflowBlock.Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == null) throw new ArgumentNullException(nameof(exception)); TrySetResult(false); } @@ -1565,10 +1541,8 @@ 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 == null) throw new ArgumentNullException(nameof(target)); - if (source == null) throw new ArgumentNullException(nameof(source)); return new EncapsulatingPropagator(target, source); } @@ -1597,10 +1571,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == null) throw new ArgumentNullException(nameof(exception)); - _target.Fault(exception); } /// @@ -1757,17 +1729,10 @@ 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!!) { - // Validate arguments - if (source1 == null) throw new ArgumentNullException(nameof(source1)); - if (action1 == null) throw new ArgumentNullException(nameof(action1)); - if (source2 == null) throw new ArgumentNullException(nameof(source2)); - if (action2 == null) throw new ArgumentNullException(nameof(action2)); - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Delegate to the shared implementation return ChooseCore(source1, action1, source2, action2, null, null, dataflowBlockOptions); } @@ -1847,20 +1812,11 @@ 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!!) { - // Validate arguments - if (source1 == null) throw new ArgumentNullException(nameof(source1)); - if (action1 == null) throw new ArgumentNullException(nameof(action1)); - if (source2 == null) throw new ArgumentNullException(nameof(source2)); - if (action2 == null) throw new ArgumentNullException(nameof(action2)); - if (source3 == null) throw new ArgumentNullException(nameof(source3)); - if (action3 == null) throw new ArgumentNullException(nameof(action3)); - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Delegate to the shared implementation return ChooseCore(source1, action1, source2, action2, source3, action3, dataflowBlockOptions); } @@ -2211,9 +2167,8 @@ 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 == null) throw new ArgumentNullException(nameof(source)); return SourceObservable.From(source); } @@ -2275,10 +2230,9 @@ 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!!) { // Validate arguments - if (observer == null) throw new ArgumentNullException(nameof(observer)); Common.ContractAssertMonitorStatus(_SubscriptionLock, held: false); Task? sourceCompletionTask = Common.GetPotentiallyNotSupportedCompletionTask(_source); @@ -2579,9 +2533,8 @@ 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 == 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 3b8f05674b1242..4215ae5df957fd 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/ActionBlock.cs @@ -66,12 +66,8 @@ 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!!) { - // Validate arguments - if (action == null) throw new ArgumentNullException(nameof(action)); - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -230,10 +226,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == 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 ae3c92c2acba25..0b33c3175444f7 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchBlock.cs @@ -99,10 +99,8 @@ 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 == 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 c47a75075a31b0..e0b9d4e415ef38 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BatchedJoinBlock.cs @@ -154,10 +154,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == 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"); @@ -408,10 +406,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == 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"); @@ -608,10 +604,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == 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 e7ee8f5f1e55c8..9a5a6935d8bd88 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BroadcastBlock.cs @@ -62,11 +62,8 @@ 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!!) { - // Validate arguments - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -110,10 +107,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == null) throw new ArgumentNullException(nameof(exception)); - CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } @@ -1001,12 +996,8 @@ private void CompleteBlockOncePossible() } /// - internal IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) + internal IDisposable LinkTo(ITargetBlock target!!, DataflowLinkOptions linkOptions!!) { - // Validate arguments - if (target == null) throw new ArgumentNullException(nameof(target)); - if (linkOptions == 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 c4e0250d5fe002..ee6dc68b53ef51 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/BufferBlock.cs @@ -43,10 +43,8 @@ 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 == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -144,10 +142,8 @@ 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 == 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 9b336c3d6f3511..874a34fd5b61ed 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/JoinBlock.cs @@ -47,11 +47,8 @@ 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!!) { - // Validate arguments - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -139,10 +136,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == null) throw new ArgumentNullException(nameof(exception)); - Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized"); @@ -269,11 +264,8 @@ 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!!) { - // Validate arguments - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -361,10 +353,8 @@ public void Complete() } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == null) throw new ArgumentNullException(nameof(exception)); - Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._exceptionAction != null, "_sharedResources._exceptionAction not initialized"); @@ -924,10 +914,8 @@ internal override void CompleteCore(Exception? exception, bool dropPendingMessag } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == 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 72f837445a60d8..443013d7834d69 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformBlock.cs @@ -88,7 +88,7 @@ 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 (transformSync == null && transformAsync == null) throw new ArgumentNullException("transform"); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); @@ -328,10 +328,8 @@ 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 == 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 55bacb242ea747..6cb21afa18e06f 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/TransformManyBlock.cs @@ -567,10 +567,8 @@ 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 == 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 ba46828913e284..a1b97e5a12c713 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Blocks/WriteOnceBlock.cs @@ -60,11 +60,8 @@ 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!!) { - // Validate arguments - if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); - // Store the option _cloningFunction = cloningFunction; _dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); @@ -204,10 +201,8 @@ private void CompleteBlock(IList? exceptions) } /// - void IDataflowBlock.Fault(Exception exception) + void IDataflowBlock.Fault(Exception exception!!) { - if (exception == null) throw new ArgumentNullException(nameof(exception)); - CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false); } @@ -295,12 +290,8 @@ bool IReceivableSourceBlock.TryReceiveAll([NotNullWhen(true)] out IList? i } /// - public IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) + public IDisposable LinkTo(ITargetBlock target!!, DataflowLinkOptions linkOptions!!) { - // Validate arguments - if (target == null) throw new ArgumentNullException(nameof(target)); - if (linkOptions == 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 9bc5e46e678971..65ad286b4c4b1d 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs @@ -121,12 +121,8 @@ internal SourceCore( } /// - internal IDisposable LinkTo(ITargetBlock target, DataflowLinkOptions linkOptions) + internal IDisposable LinkTo(ITargetBlock target!!, DataflowLinkOptions linkOptions!!) { - // Validate arguments - if (target == null) throw new ArgumentNullException(nameof(target)); - if (linkOptions == 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 3a7d40b7d0489b..1cb9fb1d2e64c1 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,17 +15,8 @@ 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body is null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, default(CancellationToken), body); } @@ -37,17 +28,8 @@ 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body is null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, cancellationToken, body); } @@ -58,21 +40,8 @@ public static Task ForEachAsync(IEnumerable source, Cancellati /// 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (parallelOptions is null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - if (body is null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachAsync(source, parallelOptions.EffectiveMaxConcurrencyLevel, parallelOptions.EffectiveTaskScheduler, parallelOptions.CancellationToken, body); } @@ -190,17 +159,8 @@ 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body is null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, default(CancellationToken), body); } @@ -212,17 +172,8 @@ public static Task ForEachAsync(IAsyncEnumerable source, Func< /// 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body is null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachAsync(source, DefaultDegreeOfParallelism, TaskScheduler.Default, cancellationToken, body); } @@ -233,21 +184,8 @@ public static Task ForEachAsync(IAsyncEnumerable source, Cance /// 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!!) { - if (source is null) - { - throw new ArgumentNullException(nameof(source)); - } - if (parallelOptions is null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - if (body is null) - { - throw new ArgumentNullException(nameof(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 1b81cfbb8b9b4a..965c5d4d97638d 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,17 +187,8 @@ 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!!) { - if (actions == null) - { - throw new ArgumentNullException(nameof(actions)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - // 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 @@ -386,13 +377,8 @@ public static void Invoke(ParallelOptions parallelOptions, params Action[] 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, Action body) + public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action body!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForWorker( fromInclusive, toExclusive, s_defaultParallelOptions, @@ -415,13 +401,8 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForWorker64( fromInclusive, toExclusive, s_defaultParallelOptions, body, null, null, null, null); @@ -454,17 +435,8 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForWorker( fromInclusive, toExclusive, parallelOptions, body, null, null, null, null); @@ -497,17 +469,8 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForWorker64( fromInclusive, toExclusive, parallelOptions, body, null, null, null, null); @@ -553,13 +516,8 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForWorker( fromInclusive, toExclusive, s_defaultParallelOptions, null, body, null, null, null); @@ -583,13 +541,8 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForWorker64( fromInclusive, toExclusive, s_defaultParallelOptions, null, body, null, null, null); @@ -624,17 +577,8 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForWorker( fromInclusive, toExclusive, parallelOptions, null, body, null, null, null); @@ -669,18 +613,9 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForWorker64( fromInclusive, toExclusive, parallelOptions, null, body, null, null, null); @@ -726,23 +661,10 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - return ForWorker( fromInclusive, toExclusive, s_defaultParallelOptions, null, null, body, localInit, localFinally); @@ -788,23 +710,10 @@ public static ParallelLoopResult For( /// public static ParallelLoopResult For( long fromInclusive, long toExclusive, - Func localInit, - Func body, - Action localFinally) + Func localInit!!, + Func body!!, + Action localFinally!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - return ForWorker64( fromInclusive, toExclusive, s_defaultParallelOptions, null, null, body, localInit, localFinally); @@ -860,28 +769,11 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForWorker( fromInclusive, toExclusive, parallelOptions, null, null, body, localInit, localFinally); @@ -937,29 +829,11 @@ 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!!) { - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - - return ForWorker64( fromInclusive, toExclusive, parallelOptions, null, null, body, localInit, localFinally); @@ -1538,17 +1412,8 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachWorker( source, s_defaultParallelOptions, body, null, null, null, null, null, null); } @@ -1583,21 +1448,8 @@ public static ParallelLoopResult ForEach(IEnumerable source, A /// 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForEachWorker( source, parallelOptions, body, null, null, null, null, null, null); } @@ -1623,17 +1475,8 @@ public static ParallelLoopResult ForEach(IEnumerable source, P /// 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachWorker( source, s_defaultParallelOptions, null, body, null, null, null, null, null); } @@ -1670,21 +1513,8 @@ public static ParallelLoopResult ForEach(IEnumerable source, A /// 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForEachWorker( source, parallelOptions, null, body, null, null, null, null, null); } @@ -1710,17 +1540,8 @@ public static ParallelLoopResult ForEach(IEnumerable source, P /// 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return ForEachWorker( source, s_defaultParallelOptions, null, null, body, null, null, null, null); } @@ -1757,21 +1578,8 @@ public static ParallelLoopResult ForEach(IEnumerable source, A /// 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForEachWorker( source, parallelOptions, null, null, body, null, null, null, null); } @@ -1817,26 +1625,9 @@ public static ParallelLoopResult ForEach(IEnumerable source, P /// 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - return ForEachWorker( source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -1893,31 +1684,10 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForEachWorker( source, parallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -1963,26 +1733,9 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - return ForEachWorker( source, s_defaultParallelOptions, null, null, null, null, body, localInit, localFinally); } @@ -2039,30 +1792,9 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return ForEachWorker( source, parallelOptions, null, null, null, null, body, localInit, localFinally); } @@ -2291,18 +2023,9 @@ private static ParallelLoopResult ForEachWorker( /// /// public static ParallelLoopResult ForEach( - Partitioner source, - Action body) + Partitioner source!!, + Action body!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return PartitionerForEachWorker(source, s_defaultParallelOptions, body, null, null, null, null, null, null); } @@ -2350,18 +2073,9 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source, - Action body) + Partitioner source!!, + Action body!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - return PartitionerForEachWorker(source, s_defaultParallelOptions, null, body, null, null, null, null, null); } @@ -2412,18 +2126,9 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source, - Action body) + OrderablePartitioner source!!, + Action body!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); @@ -2494,28 +2199,11 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source, - Func localInit, - Func body, - Action localFinally) + Partitioner source!!, + Func localInit!!, + Func body!!, + Action localFinally!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - return PartitionerForEachWorker(source, s_defaultParallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -2584,28 +2272,11 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source, - Func localInit, - Func body, - Action localFinally) + OrderablePartitioner source!!, + Func localInit!!, + Func body!!, + Action localFinally!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); @@ -2667,23 +2338,10 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source, - ParallelOptions parallelOptions, - Action body) + Partitioner source!!, + ParallelOptions parallelOptions!!, + Action body!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return PartitionerForEachWorker(source, parallelOptions, body, null, null, null, null, null, null); } @@ -2742,23 +2400,10 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - Partitioner source, - ParallelOptions parallelOptions, - Action body) + Partitioner source!!, + ParallelOptions parallelOptions!!, + Action body!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return PartitionerForEachWorker(source, parallelOptions, null, body, null, null, null, null, null); } @@ -2820,23 +2465,10 @@ public static ParallelLoopResult ForEach( /// /// public static ParallelLoopResult ForEach( - OrderablePartitioner source, - ParallelOptions parallelOptions, - Action body) + OrderablePartitioner source!!, + ParallelOptions parallelOptions!!, + Action body!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); @@ -2918,33 +2550,12 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - return PartitionerForEachWorker(source, parallelOptions, null, null, null, body, null, localInit, localFinally); } @@ -3024,33 +2635,12 @@ 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!!) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (body == null) - { - throw new ArgumentNullException(nameof(body)); - } - if (localInit == null) - { - throw new ArgumentNullException(nameof(localInit)); - } - if (localFinally == null) - { - throw new ArgumentNullException(nameof(localFinally)); - } - if (parallelOptions == null) - { - throw new ArgumentNullException(nameof(parallelOptions)); - } - if (!source.KeysNormalized) { throw new InvalidOperationException(SR.Parallel_ForEach_OrderedPartitionerKeysNotNormalized); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs index d2af113ed8f63e..7b16ffc28bda48 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs @@ -286,11 +286,7 @@ internal Transaction(DistributedTransaction distributedTransaction) internal Transaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior) { TransactionManager.ValidateIsolationLevel(isoLevel); - - if (superior == null) - { - throw new ArgumentNullException(nameof(superior)); - } + ArgumentNullException.ThrowIfNull(superior); _isoLevel = isoLevel; @@ -504,10 +500,7 @@ public Enlistment EnlistDurable( throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } - if (enlistmentNotification == null) - { - throw new ArgumentNullException(nameof(enlistmentNotification)); - } + ArgumentNullException.ThrowIfNull(enlistmentNotification); if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { @@ -558,10 +551,7 @@ public Enlistment EnlistDurable( throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } - if (singlePhaseNotification == null) - { - throw new ArgumentNullException(nameof(singlePhaseNotification)); - } + ArgumentNullException.ThrowIfNull(singlePhaseNotification); if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { @@ -657,10 +647,7 @@ public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, throw new ObjectDisposedException(nameof(Transaction)); } - if (enlistmentNotification == null) - { - throw new ArgumentNullException(nameof(enlistmentNotification)); - } + ArgumentNullException.ThrowIfNull(enlistmentNotification); if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { @@ -702,10 +689,7 @@ public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotificatio throw new ObjectDisposedException(nameof(Transaction)); } - if (singlePhaseNotification == null) - { - throw new ArgumentNullException(nameof(singlePhaseNotification)); - } + ArgumentNullException.ThrowIfNull(singlePhaseNotification); if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { @@ -990,10 +974,7 @@ public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promo throw new ObjectDisposedException(nameof(Transaction)); } - if (promotableSinglePhaseNotification == null) - { - throw new ArgumentNullException(nameof(promotableSinglePhaseNotification)); - } + ArgumentNullException.ThrowIfNull(promotableSinglePhaseNotification); if (promoterType == Guid.Empty) { @@ -1042,15 +1023,8 @@ public Enlistment PromoteAndEnlistDurable(Guid resourceManagerIdentifier, throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } - if (promotableNotification == null) - { - throw new ArgumentNullException(nameof(promotableNotification)); - } - - if (enlistmentNotification == null) - { - throw new ArgumentNullException(nameof(enlistmentNotification)); - } + ArgumentNullException.ThrowIfNull(promotableNotification); + ArgumentNullException.ThrowIfNull(enlistmentNotification); if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired) { @@ -1091,10 +1065,7 @@ public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotificati throw new ObjectDisposedException(nameof(Transaction)); } - if (promotableNotification == null) - { - throw new ArgumentNullException(nameof(promotableNotification)); - } + ArgumentNullException.ThrowIfNull(promotableNotification); if (distributedTransactionIdentifier == Guid.Empty) { 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 d47da0914ef205..e257b162577815 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs @@ -60,18 +60,8 @@ 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!!) { - if (null == transaction) - { - throw new ArgumentNullException(nameof(transaction)); - } - - if (null == whereabouts) - { - throw new ArgumentNullException(nameof(whereabouts)); - } - TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { @@ -93,13 +83,8 @@ public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts return cookie; } - public static Transaction GetTransactionFromExportCookie(byte[] cookie) + public static Transaction GetTransactionFromExportCookie(byte[] cookie!!) { - if (null == cookie) - { - throw new ArgumentNullException(nameof(cookie)); - } - if (cookie.Length < 32) { throw new ArgumentException(SR.InvalidArgument, nameof(cookie)); @@ -169,13 +154,8 @@ public static byte[] GetTransmitterPropagationToken(Transaction transaction) return token; } - public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken) + public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken!!) { - if (null == propagationToken) - { - throw new ArgumentNullException(nameof(propagationToken)); - } - if (propagationToken.Length < 24) { throw new ArgumentException(SR.InvalidArgument, nameof(propagationToken)); @@ -240,13 +220,8 @@ public static IDtcTransaction GetDtcTransaction(Transaction transaction) return transactionNative; } - public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative) + public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative!!) { - if (null == transactionNative) - { - throw new ArgumentNullException(nameof(transactionNative)); - } - TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { @@ -280,13 +255,8 @@ public static byte[] GetWhereabouts() return returnValue; } - internal static DistributedTransaction GetDistributedTransactionFromTransmitterPropagationToken(byte[] propagationToken) + internal static DistributedTransaction GetDistributedTransactionFromTransmitterPropagationToken(byte[] propagationToken!!) { - if (null == propagationToken) - { - throw new ArgumentNullException(nameof(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 4ccd3c5f17bc50..456c7f9fe82bd9 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -110,10 +110,7 @@ public static HostCurrentTransactionCallback? HostCurrentCallback { // Note do not add trace notifications to this method. It is called // at the startup of SQLCLR and tracing has too much working set overhead. - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); lock (ClassSyncObject) { 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 365b6c6bcfb25c..2f03ff684a174e 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/HttpUtility.cs @@ -80,18 +80,8 @@ 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!!) { - if (query == null) - { - throw new ArgumentNullException(nameof(query)); - } - - if (encoding == null) - { - throw new ArgumentNullException(nameof(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 658665d3c66614..7aab010e301d7c 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 @@ -55,10 +55,8 @@ internal static void HtmlAttributeEncode(string? value, TextWriter output) { return; } - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } + + ArgumentNullException.ThrowIfNull(output); HtmlAttributeEncodeInternal(value, output); } @@ -110,26 +108,16 @@ 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!!) { - if (output == null) - { - throw new ArgumentNullException(nameof(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!!) { - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - output.Write(WebUtility.HtmlEncode(value)); } @@ -647,10 +635,7 @@ private static bool ValidateUrlEncodingParameters([NotNullWhen(true)] byte[]? by return false; } - if (bytes == null) - { - throw new ArgumentNullException(nameof(bytes)); - } + ArgumentNullException.ThrowIfNull(bytes); if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); 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 2f0db1203faca7..18c09a798794cd 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 @@ -17,17 +17,13 @@ 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!!) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); DisplayX509Certificate(certificate, IntPtr.Zero); } - public static void DisplayCertificate(X509Certificate2 certificate, IntPtr hwndParent) + public static void DisplayCertificate(X509Certificate2 certificate!!, IntPtr hwndParent) { - if (certificate == null) - throw new ArgumentNullException(nameof(certificate)); DisplayX509Certificate(certificate, hwndParent); } @@ -82,10 +78,8 @@ private static void DisplayX509Certificate(X509Certificate2 certificate, IntPtr } } - 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) { - if (certificates == null) - throw new ArgumentNullException(nameof(certificates)); if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection) throw new ArgumentException(SR.Format(SR.Enum_InvalidValue, nameof(selectionFlag))); diff --git a/src/tests/Common/Coreclr.TestWrapper/CoreclrTestWrapperLib.cs b/src/tests/Common/Coreclr.TestWrapper/CoreclrTestWrapperLib.cs index 91e7f8c461c196..23bbdc5ca48bf2 100644 --- a/src/tests/Common/Coreclr.TestWrapper/CoreclrTestWrapperLib.cs +++ b/src/tests/Common/Coreclr.TestWrapper/CoreclrTestWrapperLib.cs @@ -61,7 +61,7 @@ public unsafe struct ProcessEntry32W public static extern bool Process32NextW(IntPtr snapshot, ref ProcessEntry32W entry); } - static class libproc + static class @libproc { [DllImport(nameof(libproc))] private static extern int proc_listchildpids(int ppid, int[] buffer, int byteSize); diff --git a/src/tests/issues.targets b/src/tests/issues.targets index 49579ecd10dbc7..2a964532c85504 100644 --- a/src/tests/issues.targets +++ b/src/tests/issues.targets @@ -189,6 +189,9 @@ TraceEvent can't parse unaligned floats on arm32 + + https://github.com/dotnet/runtime/issues/64986 + TraceEvent can't parse unaligned floats on arm32