diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 3d3613c1860..5878e5f029e 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -43,10 +43,7 @@ internal class ParagraphBuilder : INotifyPropertyChanged /// Paragraph we will be adding lines to in BuildParagraph. internal ParagraphBuilder(Paragraph paragraph) { - if (paragraph == null) - { - throw new ArgumentNullException("paragraph"); - } + ArgumentNullException.ThrowIfNull(paragraph); this.paragraph = paragraph; this.boldSpans = new List(); @@ -185,10 +182,7 @@ internal void HighlightAllInstancesOf(string search, bool caseSensitive, bool wh /// True if the text should be bold. internal void AddText(string str, bool bold) { - if (str == null) - { - throw new ArgumentNullException("str"); - } + ArgumentNullException.ThrowIfNull(str); if (str.Length == 0) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs index dff537f00bb..27c45ef288b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs @@ -31,10 +31,7 @@ public class IntegralConverter : IMultiValueConverter /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs index 55b57d76a3f..efefb08bae9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs @@ -22,10 +22,7 @@ public class InverseBooleanConverter : IValueConverter /// The inverted boolean value. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); var boolValue = (bool)value; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs index 83cd762198f..dbd806a64d6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs @@ -31,10 +31,7 @@ public class IsEqualConverter : IMultiValueConverter /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs index a2e2b144ad6..d8cf0b253aa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs @@ -23,10 +23,7 @@ public class StringFormatConverter : IValueConverter /// The formatted string. public object Convert(object value, Type targetType, Object parameter, CultureInfo culture) { - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); string str = (string)value; string formatString = (string)parameter; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs index c6bcfcb1737..9cc60c8411c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs @@ -83,10 +83,7 @@ public static class Utilities /// The specified value is a null reference. public static bool AreAllItemsOfType(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); foreach (object item in items) { @@ -108,10 +105,7 @@ public static bool AreAllItemsOfType(IEnumerable items) /// The specified value is a null reference. public static T Find(this IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); foreach (object item in items) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs index 85a7d00a61f..868e9a9b25b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs @@ -27,15 +27,9 @@ public class VisualToAncestorDataConverter : IValueConverter /// The specified value is a null reference. public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); Type dataType = (Type)parameter; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs index cc18509092f..d005dd909ee 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs @@ -20,10 +20,7 @@ internal class WeakEventListener : IWeakEventListener where TEventAr /// The handler for the event. public WeakEventListener(EventHandler handler) { - if (handler == null) - { - throw new ArgumentNullException("handler"); - } + ArgumentNullException.ThrowIfNull(handler); this.realHander = handler; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 23ff80d9974..b0839c6ccd2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -153,10 +153,7 @@ public bool IsEmpty /// The specified value does not have a parent that supports removal. public static void RemoveFromParent(FrameworkElement element) { - if (element == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(element); // If the element has already been detached, do nothing \\ if (element.Parent == null) @@ -215,10 +212,7 @@ public static void RemoveFromParent(FrameworkElement element) /// The specified value does not have a parent that supports removal. public static void AddChild(FrameworkElement parent, FrameworkElement element) { - if (element == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(element); if (parent == null) { @@ -310,10 +304,8 @@ public static List FindVisualChildren(DependencyObject obj) where T : DependencyObject { Debug.Assert(obj != null, "obj is null"); - if (obj == null) - { - throw new ArgumentNullException("obj"); - } + + ArgumentNullException.ThrowIfNull(obj); List childrenOfType = new List(); @@ -348,10 +340,7 @@ public static List FindVisualChildren(DependencyObject obj) public static T FindVisualAncestorData(this DependencyObject obj) where T : class { - if (obj == null) - { - throw new ArgumentNullException("obj"); - } + ArgumentNullException.ThrowIfNull(obj); FrameworkElement parent = obj.FindVisualAncestor(); @@ -413,10 +402,7 @@ public static T FindVisualAncestor(this DependencyObject @object) where T : c /// The specified value is a null reference. public static bool TryExecute(this RoutedCommand command, object parameter, IInputElement target) { - if (command == null) - { - throw new ArgumentNullException("command"); - } + ArgumentNullException.ThrowIfNull(command); if (command.CanExecute(parameter, target)) { @@ -437,10 +423,7 @@ public static bool TryExecute(this RoutedCommand command, object parameter, IInp /// The reference to the child, or null if the template part wasn't found. public static T GetOptionalTemplateChild(Control templateParent, string childName) where T : FrameworkElement { - if (templateParent == null) - { - throw new ArgumentNullException("templateParent"); - } + ArgumentNullException.ThrowIfNull(templateParent); if (string.IsNullOrEmpty(childName)) { @@ -566,10 +549,7 @@ public static RoutedPropertyChangedEventArgs CreateRoutedPropertyChangedEvent /// The specified index is not valid for the specified collection. public static void ChangeIndex(ItemCollection items, object item, int newIndex) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); if (!items.Contains(item)) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs index 4cdf51f63f6..c371a6391b5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs @@ -38,10 +38,7 @@ public ResizerGripThicknessConverter() /// A converted value. If the method returns nullNothingnullptra null reference (Nothing in Visual Basic), the valid null value is used. public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (object.ReferenceEquals(values[0], DependencyProperty.UnsetValue) || object.ReferenceEquals(values[1], DependencyProperty.UnsetValue)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs index bd5faf32d63..cd5e40a8bd9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs @@ -36,10 +36,7 @@ public override IPropertyValueGetter PropertyValueGetter set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.propertyValueGetter = value; } @@ -106,15 +103,9 @@ public override ICollection CreateDefaultFilterRulesForPropertyValue /// public override void TransferValues(FilterRule oldRule, FilterRule newRule) { - if (oldRule == null) - { - throw new ArgumentNullException("oldRule"); - } + ArgumentNullException.ThrowIfNull(oldRule); - if (newRule == null) - { - throw new ArgumentNullException("newRule"); - } + ArgumentNullException.ThrowIfNull(newRule); if (this.TryTransferValuesAsSingleValueComparableValueFilterRule(oldRule, newRule)) { @@ -130,10 +121,7 @@ public override void TransferValues(FilterRule oldRule, FilterRule newRule) /// public override void ClearValues(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); if (this.TryClearValueFromSingleValueComparableValueFilterRule(rule)) { @@ -163,10 +151,7 @@ public override void ClearValues(FilterRule rule) /// public override string GetErrorMessageForInvalidValue(string value, Type typeToParseTo) { - if (typeToParseTo == null) - { - throw new ArgumentNullException("typeToParseTo"); - } + ArgumentNullException.ThrowIfNull(typeToParseTo); bool isNumericType = typeToParseTo == typeof(byte) || typeToParseTo == typeof(sbyte) @@ -222,10 +207,7 @@ private object GetValueFromValidatingValue(FilterRule rule, string propertyName) Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Type ruleType = rule.GetType(); @@ -241,10 +223,7 @@ private void SetValueOnValidatingValue(FilterRule rule, string propertyName, obj Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Type ruleType = rule.GetType(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 3e811368476..cf885d813c5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -145,10 +145,7 @@ public FilterExpressionNode FilterExpression /// public void AddFilterExpressionProvider(IFilterExpressionProvider provider) { - if (provider == null) - { - throw new ArgumentNullException("provider"); - } + ArgumentNullException.ThrowIfNull(provider); this.filterExpressionProviders.Add(provider); provider.FilterExpressionChanged += this.FilterProvider_FilterExpressionChanged; @@ -162,10 +159,7 @@ public void AddFilterExpressionProvider(IFilterExpressionProvider provider) /// public void RemoveFilterExpressionProvider(IFilterExpressionProvider provider) { - if (provider == null) - { - throw new ArgumentNullException("provider"); - } + ArgumentNullException.ThrowIfNull(provider); this.filterExpressionProviders.Remove(provider); provider.FilterExpressionChanged -= this.FilterProvider_FilterExpressionChanged; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs index b7a26757b21..77460f61fc9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs @@ -32,10 +32,7 @@ public Exception Exception /// public FilterExceptionEventArgs(Exception exception) { - if (exception == null) - { - throw new ArgumentNullException("exception"); - } + ArgumentNullException.ThrowIfNull(exception); this.Exception = exception; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs index f255973dce8..0227362bf28 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs @@ -52,10 +52,7 @@ public FilterExpressionAndOperatorNode() /// public FilterExpressionAndOperatorNode(IEnumerable children) { - if (children == null) - { - throw new ArgumentNullException("children"); - } + ArgumentNullException.ThrowIfNull(children); this.children.AddRange(children); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs index f6bfd17377b..3161dc30283 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs @@ -38,10 +38,7 @@ public FilterRule Rule /// public FilterExpressionOperandNode(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.Rule = rule; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs index 201316a433e..ff92e42cf2d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs @@ -52,10 +52,7 @@ public FilterExpressionOrOperatorNode() /// public FilterExpressionOrOperatorNode(IEnumerable children) { - if (children == null) - { - throw new ArgumentNullException("children"); - } + ArgumentNullException.ThrowIfNull(children); this.children.AddRange(children); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs index 75019cdbf5d..b61c9933aef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs @@ -32,10 +32,7 @@ public static FilterRuleCustomizationFactory FactoryInstance set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); factoryInstance = value; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs index 1ccc3d1d227..ce8728c873e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs @@ -27,10 +27,7 @@ public static class FilterRuleExtensions /// public static FilterRule DeepCopy(this FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Debug.Assert(rule.GetType().IsSerializable, "rule is serializable"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index e8927c74826..f1bf8520a99 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -76,10 +76,7 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl throw new ArgumentNullException("propertyDisplayName"); } - if (rules == null) - { - throw new ArgumentNullException("rules"); - } + ArgumentNullException.ThrowIfNull(rules); this.PropertyName = propertyName; this.DisplayName = propertyDisplayName; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs index 3440935889f..ad1f2949972 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs @@ -101,15 +101,9 @@ protected internal string GetParsedValue(out bool evaluateAsExactMatch) /// The specified value is a null reference. protected internal string GetRegexPattern(string pattern, string exactMatchPattern) { - if (pattern == null) - { - throw new ArgumentNullException("pattern"); - } + ArgumentNullException.ThrowIfNull(pattern); - if (exactMatchPattern == null) - { - throw new ArgumentNullException("exactMatchPattern"); - } + ArgumentNullException.ThrowIfNull(exactMatchPattern); Debug.Assert(this.IsValid, "is valid"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index cf9c553f6b4..beb139b0131 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -165,10 +165,7 @@ private bool TryGetCastValue(object rawValue, out T castValue) { castValue = default(T); - if (rawValue == null) - { - throw new ArgumentNullException("rawValue"); - } + ArgumentNullException.ThrowIfNull(rawValue); if (typeof(T).IsEnum) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index ea2b255063f..f33862846a9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -141,10 +141,7 @@ public string Error /// The validation rule to add. public void AddValidationRule(DataErrorInfoValidationRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.validationRules.Add(rule); @@ -162,10 +159,7 @@ public void AddValidationRule(DataErrorInfoValidationRule rule) /// The rule to remove. public void RemoveValidationRule(DataErrorInfoValidationRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.validationRules.Remove(rule); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index 35060a1b8ff..3e577d3cb9f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -154,15 +154,9 @@ public FilterRulePanel() /// public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTemplate) { - if (type == null) - { - throw new ArgumentNullException("type"); - } + ArgumentNullException.ThrowIfNull(type); - if (dataTemplate == null) - { - throw new ArgumentNullException("dataTemplate"); - } + ArgumentNullException.ThrowIfNull(dataTemplate); this.filterRuleTemplateSelector.TemplateDictionary.Add(new KeyValuePair(type, dataTemplate)); } @@ -176,10 +170,7 @@ public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTe /// public void RemoveFilterRulePanelItemContentTemplate(Type type) { - if (type == null) - { - throw new ArgumentNullException("type"); - } + ArgumentNullException.ThrowIfNull(type); this.filterRuleTemplateSelector.TemplateDictionary.Remove(type); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs index c4956063aa3..6d3b18da484 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs @@ -88,10 +88,7 @@ public FilterRulePanelController() /// public void AddFilterRulePanelItem(FilterRulePanelItem item) { - if (item == null) - { - throw new ArgumentNullException("item"); - } + ArgumentNullException.ThrowIfNull(item); int insertionIndex = this.GetInsertionIndex(item); this.filterRulePanelItems.Insert(insertionIndex, item); @@ -116,10 +113,7 @@ private void Rule_EvaluationResultInvalidated(object sender, EventArgs e) /// public void RemoveFilterRulePanelItem(FilterRulePanelItem item) { - if (item == null) - { - throw new ArgumentNullException("item"); - } + ArgumentNullException.ThrowIfNull(item); item.Rule.EvaluationResultInvalidated -= this.Rule_EvaluationResultInvalidated; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index 7f9a5afcc4c..2378f9238d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -79,10 +79,7 @@ protected internal set /// public FilterRulePanelItem(FilterRule rule, string groupId) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); if (string.IsNullOrEmpty(groupId)) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs index 0017f2a4340..28adfa82c86 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs @@ -40,10 +40,7 @@ public class InputFieldBackgroundTextConverter : IValueConverter /// public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); Type inputType = null; if (this.IsOfTypeValidatingValue(value)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs index b6471b6f653..ac9b5267f31 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs @@ -88,10 +88,7 @@ public SearchTextParser Parser set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.parser = value; } @@ -120,10 +117,7 @@ partial void OnClearTextExecutedImplementation(ExecutedRoutedEventArgs e) /// The specified value is a null reference. protected static FilterExpressionNode ConvertToFilterExpression(ICollection searchBoxItems) { - if (searchBoxItems == null) - { - throw new ArgumentNullException("searchBoxItems"); - } + ArgumentNullException.ThrowIfNull(searchBoxItems); if (searchBoxItems.Count == 0) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs index 5fa5e3e7703..10843087587 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs @@ -18,10 +18,7 @@ public class SearchTextParseResult /// The specified value is a null reference. public SearchTextParseResult(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.FilterRule = rule; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index 04ba32ece6d..c64683c7301 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -45,10 +45,7 @@ public TextFilterRule FullTextRule public bool TryAddSearchableRule(SelectorFilterRule selectorRule) where T : TextFilterRule { - if (selectorRule == null) - { - throw new ArgumentNullException("selectorRule"); - } + ArgumentNullException.ThrowIfNull(selectorRule); T textRule = selectorRule.AvailableRules.AvailableValues.Find(); @@ -193,20 +190,11 @@ protected class SearchableRule /// The specified value is a null reference. public SearchableRule(string uniqueId, SelectorFilterRule selectorFilterRule, TextFilterRule childRule) { - if (uniqueId == null) - { - throw new ArgumentNullException("uniqueId"); - } + ArgumentNullException.ThrowIfNull(uniqueId); - if (selectorFilterRule == null) - { - throw new ArgumentNullException("selectorFilterRule"); - } + ArgumentNullException.ThrowIfNull(selectorFilterRule); - if (childRule == null) - { - throw new ArgumentNullException("childRule"); - } + ArgumentNullException.ThrowIfNull(childRule); this.UniqueId = uniqueId; this.selectorFilterRule = selectorFilterRule; @@ -240,10 +228,7 @@ public string Pattern /// The specified value is a null reference. public SelectorFilterRule GetRuleWithValueSet(string value) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); SelectorFilterRule selectorRule = (SelectorFilterRule)this.selectorFilterRule.DeepCopy(); selectorRule.AvailableRules.SelectedIndex = this.selectorFilterRule.AvailableRules.AvailableValues.IndexOf(this.childRule); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs index e8708b92a15..010fbbeef75 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs @@ -38,10 +38,7 @@ public class ValidatingSelectorValueToDisplayNameConverter : IMultiValueConverte /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs index 470a7670860..8a919959968 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs @@ -59,15 +59,9 @@ internal ColumnPicker( ICollection availableColumns) : this() { - if (columns == null) - { - throw new ArgumentNullException("columns"); - } - - if (availableColumns == null) - { - throw new ArgumentNullException("availableColumns"); - } + ArgumentNullException.ThrowIfNull(columns); + + ArgumentNullException.ThrowIfNull(availableColumns); // Add visible columns to Selected list, preserving order // Note that availableColumns is not necessarily in the order diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs index 73222cae639..2761dcf36da 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs @@ -45,10 +45,7 @@ public InnerListGridView() /// The specified value is a null reference. internal InnerListGridView(ObservableCollection availableColumns) { - if (availableColumns == null) - { - throw new ArgumentNullException("availableColumns"); - } + ArgumentNullException.ThrowIfNull(availableColumns); // Setting the AvailableColumns property won't trigger CollectionChanged, so we have to do it manually \\ this.AvailableColumns = availableColumns; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index 868e17d85c4..fe9e0fdcd1e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -191,10 +191,7 @@ public void RefreshColumns() /// The specified value is a null reference. public void ApplySort(InnerListColumn column, bool shouldScrollIntoView) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); // NOTE : By setting the column here, it will be used // later to set the sorted column when the UI state diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs index 841175c97da..93e035f7bc5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs @@ -63,10 +63,7 @@ public ManagementListStateDescriptor(string name) /// public override void SaveState(ManagementList subject) { - if (subject == null) - { - throw new ArgumentNullException("subject"); - } + ArgumentNullException.ThrowIfNull(subject); this.SaveColumns(subject); this.SaveSortOrder(subject); @@ -100,10 +97,7 @@ public override void RestoreState(ManagementList subject) /// public void RestoreState(ManagementList subject, bool applyRestoredFilter) { - if (subject == null) - { - throw new ArgumentNullException("subject"); - } + ArgumentNullException.ThrowIfNull(subject); // Clear the sort, otherwise restoring columns and filters may trigger extra sorting \\ subject.List.ClearSort(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 61a1a71938c..2e9326cd909 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -48,10 +48,7 @@ public virtual bool TryGetPropertyValue(string propertyName, object value, out o throw new ArgumentException("propertyName is empty", "propertyName"); } - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); PropertyDescriptor descriptor = this.GetPropertyDescriptor(propertyName, value); if (descriptor == null) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs index 9f91f2b74e8..965a66239d0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs @@ -68,10 +68,7 @@ public InnerListColumn(UIPropertyGroupDescription dataDescription, bool isVisibl /// Whether the column should create a default binding using the specified data's property. public InnerListColumn(UIPropertyGroupDescription dataDescription, bool isVisible, bool createDefaultBinding) { - if (dataDescription == null) - { - throw new ArgumentNullException("dataDescription"); - } + ArgumentNullException.ThrowIfNull(dataDescription); GridViewColumnHeader header = new GridViewColumnHeader(); header.Content = dataDescription.DisplayContent; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 7c36244e0f1..4ac51c702d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -50,10 +50,7 @@ public IStateDescriptorFactory SavedViewFactory set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.savedViewFactory = value; } @@ -177,10 +174,7 @@ private void Evaluator_PropertyChanged(object sender, PropertyChangedEventArgs e /// The specified value is a null reference. public void AddColumn(InnerListColumn column) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); this.AddColumn(column, this.IsFilterShown); } @@ -193,10 +187,7 @@ public void AddColumn(InnerListColumn column) /// The specified value is a null reference. public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); this.List.Columns.Add(column); @@ -229,10 +220,7 @@ public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) /// The specified value is a null reference. public void AddRule(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.AddFilterRulePicker.ShortcutFilterRules.Add(new AddFilterRulePickerItem(new FilterRulePanelItem(rule, rule.DisplayName))); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index 34159c8f837..da51550c084 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -95,10 +95,7 @@ public AllModulesViewModel(Dictionary importedMod /// True not to show common parameters. public AllModulesViewModel(Dictionary importedModules, IEnumerable commands, bool noCommonParameter) { - if (commands == null) - { - throw new ArgumentNullException("commands"); - } + ArgumentNullException.ThrowIfNull(commands); this.Initialization(importedModules, commands, noCommonParameter); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index 33908ea732f..367b5d08131 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -490,10 +490,7 @@ internal static bool IsSharedParameterSetName(string name) /// The CommandViewModel corresponding to commandInfo. internal static CommandViewModel GetCommandViewModel(ModuleViewModel module, ShowCommandCommandInfo commandInfo, bool noCommonParameters) { - if (commandInfo == null) - { - throw new ArgumentNullException("commandInfo"); - } + ArgumentNullException.ThrowIfNull(commandInfo); CommandViewModel returnValue = new CommandViewModel(); returnValue.commandInfo = commandInfo; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index 95e45123d22..950dbe93758 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -67,10 +67,7 @@ public class ModuleViewModel : INotifyPropertyChanged /// All loaded modules. public ModuleViewModel(string name, Dictionary importedModules) { - if (name == null) - { - throw new ArgumentNullException("name"); - } + ArgumentNullException.ThrowIfNull(name); this.name = name; this.commands = new List(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 1521aab7742..9d59ca3dc1d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -45,15 +45,9 @@ public ParameterSetViewModel( string name, List parameters) { - if (name == null) - { - throw new ArgumentNullException("name"); - } + ArgumentNullException.ThrowIfNull(name); - if (parameters == null) - { - throw new ArgumentNullException("parameters"); - } + ArgumentNullException.ThrowIfNull(parameters); parameters.Sort(Compare); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs index ccd2fd635c8..32eb8271938 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -48,15 +48,9 @@ public class ParameterViewModel : INotifyPropertyChanged /// The name of the parameter set this parameter is in. public ParameterViewModel(ShowCommandParameterInfo parameter, string parameterSetName) { - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); - if (parameterSetName == null) - { - throw new ArgumentNullException("parameterSetName"); - } + ArgumentNullException.ThrowIfNull(parameterSetName); this.parameter = parameter; this.parameterSetName = parameterSetName; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index cca50c4bb91..58a1fbb4c2d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -577,8 +577,9 @@ private TSession GetImpliedSession() /// if successful method invocations should emit downstream the being operated on. public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { - if (objectInstance == null) throw new ArgumentNullException(nameof(objectInstance)); - if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + ArgumentNullException.ThrowIfNull(objectInstance); + + ArgumentNullException.ThrowIfNull(methodInvocationInfo); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { @@ -603,7 +604,7 @@ public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocat /// Method invocation details. public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) { - if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + ArgumentNullException.ThrowIfNull(methodInvocationInfo); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 0ffa5bdf98f..4ad6ecc9698 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -54,10 +54,7 @@ protected CimJobException( SerializationInfo info, StreamingContext context) : base(info, context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); _errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord)); } @@ -69,10 +66,7 @@ protected CimJobException( /// The that contains contextual information about the source or destination. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); base.GetObjectData(info, context); info.AddValue("errorRecord", _errorRecord); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 74f0f922cc5..7a3eb0ce326 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -352,7 +352,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) /// The only kind of exception this method can throw. internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType) { - if (expectedDotNetType == null) { throw new ArgumentNullException(nameof(expectedDotNetType)); } + ArgumentNullException.ThrowIfNull(expectedDotNetType); if (cimObject == null) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index d2e920b7f9d..2c5c91fb1c8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -319,10 +319,7 @@ public override void AddQueryOption(string optionName, object optionValue) throw new ArgumentNullException(nameof(optionName)); } - if (optionValue == null) - { - throw new ArgumentNullException(nameof(optionValue)); - } + ArgumentNullException.ThrowIfNull(optionValue); this.queryOptions[optionName] = optionValue; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 3f2c6740dcf..8bfa485ff24 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2962,9 +2962,8 @@ public override void GetObjectData( { base.GetObjectData(info, context); - if (info == null) - throw new ArgumentNullException(nameof(info)); - + ArgumentNullException.ThrowIfNull(info); + info.AddValue("ProcessName", _processName); } #endregion Serialization diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 69fb051519f..d6190573a38 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -2569,10 +2569,7 @@ public ServiceCommandException(string message, Exception innerException) protected ServiceCommandException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); _serviceName = info.GetString("ServiceName"); } @@ -2583,10 +2580,7 @@ protected ServiceCommandException(SerializationInfo info, StreamingContext conte /// Streaming context. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); base.GetObjectData(info, context); info.AddValue("ServiceName", _serviceName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index c42977996ae..1d1c235165b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -951,10 +951,7 @@ internal static IList BuildPropertyNames(PSObject source, IList /// Converted string. internal string ConvertPropertyNamesCSV(IList propertyNames) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); _outputString.Clear(); bool first = true; @@ -1018,10 +1015,7 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) /// internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); _outputString.Clear(); bool first = true; @@ -1107,10 +1101,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN /// ToString() value. internal static string GetToStringValueForProperty(PSPropertyInfo property) { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } + ArgumentNullException.ThrowIfNull(property); string value = null; try @@ -1272,15 +1263,9 @@ internal class ImportCsvHelper internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList header, string typeName, StreamReader streamReader) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); - if (streamReader == null) - { - throw new ArgumentNullException(nameof(streamReader)); - } + ArgumentNullException.ThrowIfNull(streamReader); _cmdlet = cmdlet; _delimiter = delimiter; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index c7f2c622c08..d9de50ef52c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -58,20 +58,11 @@ internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCo /// An array of types to add. internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); - if (displayNames == null) - { - throw new ArgumentNullException(nameof(displayNames)); - } + ArgumentNullException.ThrowIfNull(displayNames); - if (types == null) - { - throw new ArgumentNullException(nameof(types)); - } + ArgumentNullException.ThrowIfNull(types); try { @@ -177,10 +168,7 @@ private void AddExtraProperties(PSObject staleObject, PSObject liveObject) /// internal void AddItem(PSObject livePSObject) { - if (livePSObject == null) - { - throw new ArgumentNullException(nameof(livePSObject)); - } + ArgumentNullException.ThrowIfNull(livePSObject); if (_headerInfo == null) { @@ -203,10 +191,7 @@ internal void AddItem(PSObject livePSObject) /// internal void AddHeteroViewItem(PSObject livePSObject) { - if (livePSObject == null) - { - throw new ArgumentNullException(nameof(livePSObject)); - } + ArgumentNullException.ThrowIfNull(livePSObject); if (_headerInfo == null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index d6e0b004bdf..c1643218ce1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -532,10 +532,7 @@ public bool Contains(T item) public void CopyTo(T[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } + ArgumentNullException.ThrowIfNull(array); if (arrayIndex < 0) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index b57be43f25f..d7ce5310c98 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -24,10 +24,7 @@ internal sealed class PSPropertyExpressionFilter /// Array of pattern strings to use. internal PSPropertyExpressionFilter(string[] wildcardPatternsStrings) { - if (wildcardPatternsStrings == null) - { - throw new ArgumentNullException(nameof(wildcardPatternsStrings)); - } + ArgumentNullException.ThrowIfNull(wildcardPatternsStrings); _wildcardPatterns = new WildcardPattern[wildcardPatternsStrings.Length]; for (int k = 0; k < wildcardPatternsStrings.Length; k++) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index 163b5d5028c..e2ba41fb3fc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandCommandInfo /// public ShowCommandCommandInfo(CommandInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.ModuleName = other.ModuleName; @@ -71,10 +68,7 @@ public ShowCommandCommandInfo(CommandInfo other) /// public ShowCommandCommandInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.ModuleName = other.Members["ModuleName"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index b12cc5651f4..f31bc93525d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -20,10 +20,7 @@ public class ShowCommandModuleInfo /// public ShowCommandModuleInfo(PSModuleInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; } @@ -37,10 +34,7 @@ public ShowCommandModuleInfo(PSModuleInfo other) /// public ShowCommandModuleInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index 88a75dfe610..9bf79c5bd76 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandParameterInfo /// public ShowCommandParameterInfo(CommandParameterInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.IsMandatory = other.IsMandatory; @@ -50,10 +47,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) /// public ShowCommandParameterInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.IsMandatory = (bool)(other.Members["IsMandatory"].Value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index 75f0675eb87..c5ec1c74c08 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandParameterSetInfo /// public ShowCommandParameterSetInfo(CommandParameterSetInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.IsDefault = other.IsDefault; @@ -41,10 +38,7 @@ public ShowCommandParameterSetInfo(CommandParameterSetInfo other) /// public ShowCommandParameterSetInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.IsDefault = (bool)(other.Members["IsDefault"].Value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index 1daf0350dbc..01da285a1d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -21,10 +21,7 @@ public class ShowCommandParameterType /// public ShowCommandParameterType(Type other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.FullName = other.FullName; if (other.IsEnum) @@ -51,10 +48,7 @@ public ShowCommandParameterType(Type other) /// public ShowCommandParameterType(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.IsEnum = (bool)(other.Members["IsEnum"].Value); this.FullName = other.Members["FullName"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 9876d0a2ca2..50a88bb6754 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -99,7 +99,7 @@ public int MaximumFollowRelLink /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); var baseResponseStream = StreamHelper.GetResponseStream(response); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index c47ee9641ca..06da66dd868 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -762,7 +762,7 @@ private Uri PrepareUri(Uri uri) private static Uri CheckProtocol(Uri uri) { - if (uri == null) { throw new ArgumentNullException(nameof(uri)); } + ArgumentNullException.ThrowIfNull(uri); if (!uri.IsAbsoluteUri) { @@ -780,8 +780,7 @@ private string QualifyFilePath(string path) private static string FormatDictionary(IDictionary content) { - if (content == null) - throw new ArgumentNullException(nameof(content)); + ArgumentNullException.ThrowIfNull(content); StringBuilder bodyBuilder = new(); foreach (string key in content.Keys) @@ -1181,7 +1180,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) internal virtual void FillRequestStream(HttpRequestMessage request) { - if (request == null) { throw new ArgumentNullException(nameof(request)); } + ArgumentNullException.ThrowIfNull(request); // set the content type if (ContentType != null) @@ -1352,9 +1351,9 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { - if (client == null) { throw new ArgumentNullException(nameof(client)); } + ArgumentNullException.ThrowIfNull(client); - if (request == null) { throw new ArgumentNullException(nameof(request)); } + ArgumentNullException.ThrowIfNull(request); // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; @@ -1486,7 +1485,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); } #endregion Virtual Methods @@ -1679,8 +1678,8 @@ protected override void ProcessRecord() /// internal long SetRequestContent(HttpRequestMessage request, byte[] content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); + if (content == null) return 0; @@ -1702,8 +1701,7 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) /// internal long SetRequestContent(HttpRequestMessage request, string content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); if (content == null) return 0; @@ -1751,8 +1749,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); if (xmlNode == null) return 0; @@ -1788,10 +1785,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (contentStream == null) - throw new ArgumentNullException(nameof(contentStream)); + ArgumentNullException.ThrowIfNull(request); + + ArgumentNullException.ThrowIfNull(contentStream); var streamContent = new StreamContent(contentStream); request.Content = streamContent; @@ -1811,15 +1807,9 @@ internal long SetRequestContent(HttpRequestMessage request, Stream contentStream /// internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); - if (multipartContent == null) - { - throw new ArgumentNullException(nameof(multipartContent)); - } + ArgumentNullException.ThrowIfNull(multipartContent); request.Content = multipartContent; @@ -1828,10 +1818,9 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon internal long SetRequestContent(HttpRequestMessage request, IDictionary content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (content == null) - throw new ArgumentNullException(nameof(content)); + ArgumentNullException.ThrowIfNull(request); + + ArgumentNullException.ThrowIfNull(content); string body = FormatDictionary(content); return (SetRequestContent(request, body)); @@ -1884,10 +1873,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr /// If true, collection types in will be enumerated. If false, collections will be treated as single value. private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { - if (formData == null) - { - throw new ArgumentNullException(nameof(formData)); - } + ArgumentNullException.ThrowIfNull(formData); // It is possible that the dictionary keys or values are PSObject wrapped depending on how the dictionary is defined and assigned. // Before processing the field name and value we need to ensure we are working with the base objects and not the PSObject wrappers. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index f13ad1aa4a3..d4490019772 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -32,7 +32,7 @@ public InvokeWebRequestCommand() : base() /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 226a981f8a2..ddba7af774e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -13,10 +13,7 @@ internal class WebProxy : IWebProxy internal WebProxy(Uri address) { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); _proxyAddress = address; } @@ -48,10 +45,7 @@ internal bool UseDefaultCredentials public Uri GetProxy(Uri destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); if (destination.IsLoopback) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 8e156152020..c9f99c524fa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -152,10 +152,7 @@ public static object ConvertFromJson(string input, bool returnHashtable, out Err [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] public static object ConvertFromJson(string input, bool returnHashtable, int? maxDepth, out ErrorRecord error) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullException.ThrowIfNull(input); error = null; try diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 9314cfd1a5d..afa17912244 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -290,10 +290,7 @@ internal static class StreamHelper internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, CancellationToken cancellationToken) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); Task copyTask = input.CopyToAsync(output, cancellationToken); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index 7ae437525dd..4a38d14845c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -330,15 +330,9 @@ internal TracePipelineWriter( bool writeError, Collection matchingSources) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } - - if (matchingSources == null) - { - throw new ArgumentNullException(nameof(matchingSources)); - } + ArgumentNullException.ThrowIfNull(cmdlet); + + ArgumentNullException.ThrowIfNull(matchingSources); _cmdlet = cmdlet; _writeError = writeError; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index ab2698ab7ec..abe0d59b43a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -771,7 +771,7 @@ public class ConsoleColorProxy public ConsoleColorProxy(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException(nameof(ui)); + ArgumentNullException.ThrowIfNull(ui); _ui = ui; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 345a6dd0154..6dfd5d54e6f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -49,10 +49,7 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray /// public static int Start([MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] args, int argc) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(args); #if DEBUG if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && args[0]!.Equals("-isswait", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 404477fa6a3..99ecc222300 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -26,7 +26,7 @@ class ProgressPane internal ProgressPane(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException(nameof(ui)); + ArgumentNullException.ThrowIfNull(ui); _ui = ui; _rawui = ui.RawUI; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 9713ac0b0b5..d283a5dd298 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -437,10 +437,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe { int status = 0; - if (eventMessage == null) - { - throw new ArgumentNullException(nameof(eventMessage)); - } + ArgumentNullException.ThrowIfNull(eventMessage); if (IsEnabled(eventLevel, eventKeywords)) { @@ -508,10 +505,7 @@ public bool WriteEvent(in EventDescriptor eventDescriptor, string data) { uint status = 0; - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } + ArgumentNullException.ThrowIfNull(data); if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 9e7befb3e38..94eb340b21c 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -72,8 +72,7 @@ public EventProviderTraceListener(string providerId, string name) public EventProviderTraceListener(string providerId, string name, string delimiter) : base(name) { - if (delimiter == null) - throw new ArgumentNullException(nameof(delimiter)); + ArgumentNullException.ThrowIfNull(delimiter); if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs index 2ec7f41499c..3e6bbcafd10 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -3145,8 +3145,7 @@ internal sealed class OperatingSystem internal OperatingSystem(Version version, string servicePack) { - if (version == null) - throw new ArgumentNullException("version"); + ArgumentNullException.ThrowIfNull(version); _version = version; _servicePack = servicePack; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs index f32f33ce008..7bb4977b79d 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs @@ -709,10 +709,7 @@ public sealed class JobTriggerToCimInstanceConverter : PSTypeConverter /// True if the converter can convert the parameter to the parameter, otherwise false. public override bool CanConvertFrom(object sourceValue, Type destinationType) { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } + ArgumentNullException.ThrowIfNull(destinationType); return (sourceValue is ScheduledJobTrigger) && (destinationType.Equals(typeof(CimInstance))); } @@ -728,15 +725,9 @@ public override bool CanConvertFrom(object sourceValue, Type destinationType) /// If no conversion was possible. public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } + ArgumentNullException.ThrowIfNull(destinationType); - if (sourceValue == null) - { - throw new ArgumentNullException("sourceValue"); - } + ArgumentNullException.ThrowIfNull(sourceValue); ScheduledJobTrigger originalTrigger = (ScheduledJobTrigger) sourceValue; using (CimSession cimSession = CimSession.Create(null)) diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 95b8f4ba584..81d4ecfd870 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -61,10 +61,7 @@ public XmlDocument RootDocument /// Current server session. public CurrentConfigurations(IWSManSession serverSession) { - if (serverSession == null) - { - throw new ArgumentNullException(nameof(serverSession)); - } + ArgumentNullException.ThrowIfNull(serverSession); this.rootDocument = new XmlDocument(); this.serverSession = serverSession; @@ -117,10 +114,7 @@ public void PutConfigurationOnServer(string resourceUri) /// Path with namespace to the node from Root element. Must not end with '/'. public void RemoveOneConfiguration(string pathToNodeFromRoot) { - if (pathToNodeFromRoot == null) - { - throw new ArgumentNullException(nameof(pathToNodeFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); XmlNode nodeToRemove = this.documentElement.SelectSingleNode( @@ -150,20 +144,14 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) /// Value of the configurations. public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue) { - if (pathToNodeFromRoot == null) - { - throw new ArgumentNullException(nameof(pathToNodeFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); if (string.IsNullOrEmpty(configurationName)) { throw new ArgumentNullException(nameof(configurationName)); } - if (configurationValue == null) - { - throw new ArgumentNullException(nameof(configurationValue)); - } + ArgumentNullException.ThrowIfNull(configurationValue); XmlNode nodeToUpdate = this.documentElement.SelectSingleNode( @@ -195,10 +183,7 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati /// Value of the Node, or Null if no node present. public string GetOneConfiguration(string pathFromRoot) { - if (pathFromRoot == null) - { - throw new ArgumentNullException(nameof(pathFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathFromRoot); XmlNode requiredNode = this.documentElement.SelectSingleNode( diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index a4917ee461e..71672f3232f 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -178,10 +178,7 @@ private static string FormatResourceMsgFromResourcetextS( string resourceName, object[] args) { - if (resourceManager == null) - { - throw new ArgumentNullException(nameof(resourceManager)); - } + ArgumentNullException.ThrowIfNull(resourceManager); if (string.IsNullOrEmpty(resourceName)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index 59626f91599..930e86d4acc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -761,10 +761,7 @@ private PSStyle() private static string ValidateNoContent(string text) { - if (text is null) - { - throw new ArgumentNullException(nameof(text)); - } + ArgumentNullException.ThrowIfNull(text); var decorartedString = new ValueStringDecorated(text); if (decorartedString.ContentLength > 0) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 1640dec33b9..d8ea4ed2398 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -21,8 +21,8 @@ public sealed class MethodInvocationInfo /// Return value of the method (ok to pass if the method doesn't return anything). public MethodInvocationInfo(string name, IEnumerable parameters, MethodParameter returnValue) { - if (name == null) throw new ArgumentNullException(nameof(name)); - if (parameters == null) throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(parameters); // returnValue can be null MethodName = name; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index ab6b741280e..e52582fc985 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -17,25 +17,17 @@ public abstract class CmdletAdapter { internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, IDictionary privateData) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); if (string.IsNullOrEmpty(className)) { throw new ArgumentNullException(nameof(className)); } - if (classVersion == null) // possible and ok to have classVersion==string.Empty - { - throw new ArgumentNullException(nameof(classVersion)); - } + // possible and ok to have classVersion==string.Empty + ArgumentNullException.ThrowIfNull(classVersion); - if (privateData == null) - { - throw new ArgumentNullException(nameof(privateData)); - } + ArgumentNullException.ThrowIfNull(privateData); _cmdlet = cmdlet; _className = className; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index ece48f33d0b..3d46fbf28c2 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -6678,10 +6678,7 @@ internal sealed class PowerShellMetadataSerializer { internal object Deserialize(XmlReader reader) { - if (reader == null) - { - throw new ArgumentNullException(nameof(reader)); - } + ArgumentNullException.ThrowIfNull(reader); XmlSerializationReader1 cdxmlSerializationReader = new XmlSerializationReader1(reader); return cdxmlSerializationReader.Read50_PowerShellMetadata(); diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index ad98e0c50a1..6b1b85c125d 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -195,10 +195,7 @@ internal static string CimTypeToTypeNameDisplayString(CimType cimType) /// public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); CimProperty cimProperty = adaptedProperty.Tag as CimProperty; if (cimProperty != null) @@ -220,10 +217,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) /// public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); CimProperty cimProperty = adaptedProperty.Tag as CimProperty; if (cimProperty != null) @@ -375,10 +369,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) /// public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); if (!IsSettable(adaptedProperty)) { diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index d0e6dd7effa..7cd213a025c 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -110,10 +110,7 @@ internal CommandInfo(string name, CommandTypes type) // The name can be empty for functions and filters but it // can't be null - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Name = name; CommandType = type; diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index a492a5215fc..e2a63a527a9 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -35,10 +35,7 @@ private EngineIntrinsics() /// internal EngineIntrinsics(ExecutionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _context = context; _host = context.EngineHostInterface; diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index a0e95e083e7..e802d376a14 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -193,10 +193,7 @@ public class ErrorCategoryInfo #region ctor internal ErrorCategoryInfo(ErrorRecord errorRecord) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 78304819289..f7ffbddd852 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -817,10 +817,7 @@ public override void UnsubscribeEvent(PSEventSubscriber subscriber) /// private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) { - if (subscriber == null) - { - throw new ArgumentNullException(nameof(subscriber)); - } + ArgumentNullException.ThrowIfNull(subscriber); Delegate existingSubscriber = null; lock (_eventSubscribers) @@ -2368,10 +2365,7 @@ public class PSEventArgsCollection : IEnumerable /// Don't add events to the collection directly; use the EventManager instead internal void Add(PSEventArgs eventToAdd) { - if (eventToAdd == null) - { - throw new ArgumentNullException(nameof(eventToAdd)); - } + ArgumentNullException.ThrowIfNull(eventToAdd); _eventCollection.Add(eventToAdd); @@ -2486,10 +2480,9 @@ public PSEventJob( string name) : base(action?.ToString(), name) { - if (eventManager == null) - throw new ArgumentNullException(nameof(eventManager)); - if (subscriber == null) - throw new ArgumentNullException(nameof(subscriber)); + ArgumentNullException.ThrowIfNull(eventManager); + + ArgumentNullException.ThrowIfNull(subscriber); UsesResultsCollection = true; ScriptBlock = action; diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 3c253504f01..113ba8121b8 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -303,10 +303,7 @@ public PSTypeName[] ParameterType set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); // if '...CimInstance#Win32_Process' is specified, then exclude '...CimInstance' List filteredParameterTypes = new List(value.Length); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 5e5758340e8..2dbb12fb253 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -980,10 +980,7 @@ public InitialSessionStateEntryCollection() /// public InitialSessionStateEntryCollection(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); _internalCollection = new Collection(); @@ -1154,10 +1151,7 @@ public void Clear() /// The type of object to remove, can be null to remove any type. public void Remove(string name, object type) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); lock (_syncObject) { @@ -1192,10 +1186,7 @@ public void Remove(string name, object type) /// The item to add... public void Add(T item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); lock (_syncObject) { @@ -1209,10 +1200,7 @@ public void Add(T item) /// public void Add(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); lock (_syncObject) { @@ -1870,10 +1858,7 @@ public Microsoft.PowerShell.ExecutionPolicy ExecutionPolicy /// public void ImportPSModule(params string[] name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); foreach (string n in name) { @@ -1898,10 +1883,7 @@ internal void ClearPSModules() /// public void ImportPSModule(IEnumerable modules) { - if (modules == null) - { - throw new ArgumentNullException(nameof(modules)); - } + ArgumentNullException.ThrowIfNull(modules); foreach (var moduleSpecification in modules) { @@ -1929,10 +1911,7 @@ public void ImportPSModulesFromPath(string path) /// internal void ImportPSCoreModule(string[] name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); foreach (string n in name) { @@ -4931,10 +4910,8 @@ internal static void AnalyzePSSnapInAssembly( out string helpFile) { helpFile = null; - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + + ArgumentNullException.ThrowIfNull(assembly); cmdlets = null; aliases = null; diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index 315cf3aaf64..b539b191909 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -67,10 +67,7 @@ public ModuleSpecification(string moduleName) /// The module specification as a hashtable. public ModuleSpecification(Hashtable moduleSpecification) { - if (moduleSpecification == null) - { - throw new ArgumentNullException(nameof(moduleSpecification)); - } + ArgumentNullException.ThrowIfNull(moduleSpecification); var exception = ModuleSpecificationInitHelper(this, moduleSpecification); if (exception != null) @@ -172,10 +169,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu internal ModuleSpecification(PSModuleInfo moduleInfo) { - if (moduleInfo == null) - { - throw new ArgumentNullException(nameof(moduleInfo)); - } + ArgumentNullException.ThrowIfNull(moduleInfo); this.Name = moduleInfo.Name; this.Version = moduleInfo.Version; diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index ebc2f164c6e..9711b64f8b0 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -801,8 +801,7 @@ public Collection InvokeScript( IList input, params object[] args) { - if (script == null) - throw new ArgumentNullException(nameof(script)); + ArgumentNullException.ThrowIfNull(script); // Compile the script text into an executable script block. ScriptBlock sb = ScriptBlock.Create(_context, script); diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 6a2e6dce66d..80d70377e87 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -376,10 +376,7 @@ private static void AppendType(StringBuilder sb, string section, PSObject parent /// When the help argument is not recognized as a HelpInfo object. public static string GetHelpComments(PSObject help) { - if (help == null) - { - throw new ArgumentNullException(nameof(help)); - } + ArgumentNullException.ThrowIfNull(help); bool isHelpObject = false; foreach (string typeName in help.InternalTypeNames) diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index 754f228633a..6bdc29da198 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -151,10 +151,7 @@ internal static Collection ConvertArrayToCollection(T[] array) /// internal static bool CollectionContainsValue(IEnumerable collection, object value, IComparer comparer) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); bool result = false; diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index bde0c0f3483..d77e700e90e 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -296,10 +296,7 @@ public abstract class PSPropertyAdapter [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")] public virtual Collection GetTypeNameHierarchy(object baseObject) { - if (baseObject == null) - { - throw new ArgumentNullException(nameof(baseObject)); - } + ArgumentNullException.ThrowIfNull(baseObject); Collection types = new Collection(); diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 5e41aec1eb6..a752f9b62df 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -4732,15 +4732,9 @@ internal void Update( PSHost host, out bool failToLoadFile) { - if (filePath == null) - { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentNullException.ThrowIfNull(filePath); - if (errors == null) - { - throw new ArgumentNullException(nameof(errors)); - } + ArgumentNullException.ThrowIfNull(errors); if (isShared) { @@ -4810,10 +4804,9 @@ internal void Update( ConcurrentBag errors, bool isRemove) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - if (errors == null) - throw new ArgumentNullException(nameof(errors)); + ArgumentNullException.ThrowIfNull(type); + + ArgumentNullException.ThrowIfNull(errors); if (isShared) { diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index ac16aa4b76a..93a3e80b74b 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1702,10 +1702,7 @@ internal sealed class ReadOnlyBag : IEnumerable /// internal ReadOnlyBag(HashSet hashset) { - if (hashset == null) - { - throw new ArgumentNullException(nameof(hashset)); - } + ArgumentNullException.ThrowIfNull(hashset); _hashset = hashset; } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 612705e6d95..e241b972b38 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -1719,8 +1719,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (errorRecord == null) - throw new ArgumentNullException(nameof(errorRecord)); + ArgumentNullException.ThrowIfNull(errorRecord); if (commandRuntime != null) { diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 4723db9a1d7..db089b68333 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -212,10 +212,7 @@ public void ApplyTo(IList collectionToUpdate) /// The collection to update. public void ApplyTo(object collectionToUpdate) { - if (collectionToUpdate == null) - { - throw new ArgumentNullException(nameof(collectionToUpdate)); - } + ArgumentNullException.ThrowIfNull(collectionToUpdate); collectionToUpdate = PSObject.Base(collectionToUpdate); diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 07d17589c3b..1dace005fa7 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -6157,15 +6157,9 @@ internal class PowerShellStopper : IDisposable internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); - if (powerShell == null) - { - throw new ArgumentNullException(nameof(powerShell)); - } + ArgumentNullException.ThrowIfNull(powerShell); _powerShell = powerShell; diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 451d015fdcc..3c7d6576aaa 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1096,15 +1096,9 @@ public sealed class SteppablePipeline : IDisposable { internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) { - if (pipeline == null) - { - throw new ArgumentNullException(nameof(pipeline)); - } + ArgumentNullException.ThrowIfNull(pipeline); - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _pipeline = pipeline; _context = context; @@ -1128,10 +1122,7 @@ internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) /// Context used to figure out how to route the output and errors. public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { - if (contextToRedirectTo == null) - { - throw new ArgumentNullException(nameof(contextToRedirectTo)); - } + ArgumentNullException.ThrowIfNull(contextToRedirectTo); ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 9d80edf6500..c0bdd25740a 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -142,10 +142,7 @@ public static ScriptBlockAst ParseInput(string input, out Token[] tokens, out Pa /// The that represents the input script file. public static ScriptBlockAst ParseInput(string input, string fileName, out Token[] tokens, out ParseError[] errors) { - if (input is null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullException.ThrowIfNull(input); Parser parser = new Parser(); List tokenList = new List(); diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 54424ea4cc7..4ee07ea967d 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3884,10 +3884,7 @@ public CommentHelpInfo GetHelpContent() /// public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenCache) { - if (scriptBlockTokenCache == null) - { - throw new ArgumentNullException(nameof(scriptBlockTokenCache)); - } + ArgumentNullException.ThrowIfNull(scriptBlockTokenCache); var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); if (commentTokens != null) @@ -5577,15 +5574,9 @@ public PipelineChainAst( bool background = false) : base(extent) { - if (lhsChain == null) - { - throw new ArgumentNullException(nameof(lhsChain)); - } + ArgumentNullException.ThrowIfNull(lhsChain); - if (rhsPipeline == null) - { - throw new ArgumentNullException(nameof(rhsPipeline)); - } + ArgumentNullException.ThrowIfNull(rhsPipeline); if (chainOperator != TokenKind.AndAnd && chainOperator != TokenKind.OrOr) { @@ -10462,10 +10453,7 @@ public override Ast Copy() [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to get the underlying variable only for the UsingExpressionAst.")] public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usingExpressionAst) { - if (usingExpressionAst == null) - { - throw new ArgumentNullException(nameof(usingExpressionAst)); - } + ArgumentNullException.ThrowIfNull(usingExpressionAst); return ExtractUsingVariableImpl(usingExpressionAst); } diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index a1e7f9ede94..4efe1ff436a 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -447,10 +447,7 @@ public class WildcardPatternException : RuntimeException internal WildcardPatternException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index d5f122159ed..3f9c025d954 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -706,10 +706,8 @@ public ContainerParentJob(string command, string name, string jobType) public void AddChildJob(Job2 childJob) { AssertNotDisposed(); - if (childJob == null) - { - throw new ArgumentNullException(nameof(childJob)); - } + + ArgumentNullException.ThrowIfNull(childJob); _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : ", InstanceId.ToString()); @@ -2181,8 +2179,7 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte /// The standard StreaminContext. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - throw new ArgumentNullException(nameof(info)); + ArgumentNullException.ThrowIfNull(info); base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index f907cf922d8..53161c40fc0 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -176,10 +176,7 @@ internal static void SaveJobId(Guid instanceId, int id, string typeName) /// public Job2 NewJob(JobDefinition definition) { - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } + ArgumentNullException.ThrowIfNull(definition); JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); Job2 newJob; @@ -216,10 +213,7 @@ public Job2 NewJob(JobDefinition definition) /// public Job2 NewJob(JobInvocationInfo specification) { - if (specification == null) - { - throw new ArgumentNullException(nameof(specification)); - } + ArgumentNullException.ThrowIfNull(specification); if (specification.Definition == null) { diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 0de48ff6dfc..cf37aa7bb33 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -149,7 +149,7 @@ public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originIn private static ProgressRecord Validate(ProgressRecord progressRecord) { - if (progressRecord == null) throw new ArgumentNullException(nameof(progressRecord)); + ArgumentNullException.ThrowIfNull(progressRecord); return progressRecord; } } diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 000e544fd57..b9a0cc4dfab 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -294,7 +294,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var jobGotEnqueued = new ManualResetEventSlim(initialState: false)) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); this.AddChildJobWithoutBlocking(childJob, flags, jobGotEnqueued.Set); jobGotEnqueued.Wait(); @@ -308,7 +308,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var forwardingCancellation = new CancellationTokenSource()) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); this.AddChildJobWithoutBlocking(childJob, flags, forwardingCancellation.Cancel); this.ForwardAllResultsToCmdlet(cmdlet, forwardingCancellation.Token); @@ -368,7 +368,7 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() /// internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); this.AssertNotDisposed(); diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 23e86e9669a..a24163f66c7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -2460,10 +2460,7 @@ private List GetUsingVariableValues(List paramUsi /// A list of UsingExpressionAsts ordered by the StartOffset. private static List GetUsingVariables(ScriptBlock localScriptBlock) { - if (localScriptBlock == null) - { - throw new ArgumentNullException(nameof(localScriptBlock), "Caller needs to make sure the parameter value is not null"); - } + ArgumentNullException.ThrowIfNull(localScriptBlock, "Caller needs to make sure the parameter value is not null"); var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressions(localScriptBlock.Ast); return allUsingExprs.Select(static usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 9a50d9b8d94..700596957f6 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -168,10 +168,7 @@ public CultureInfo Culture set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _culture = value; } @@ -191,10 +188,7 @@ public CultureInfo UICulture set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _uiCulture = value; } @@ -284,10 +278,7 @@ public int OpenTimeout /// public virtual void SetSessionOptions(PSSessionOption options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.Culture != null) { @@ -1029,10 +1020,7 @@ public WSManConnectionInfo(Uri uri) /// public override void SetSessionOptions(PSSessionOption options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential != null)) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 8596e87e834..ffcb9a80672 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -820,14 +820,11 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { - if (sessionConfigurationData == null) - throw new ArgumentNullException(nameof(sessionConfigurationData)); + ArgumentNullException.ThrowIfNull(sessionConfigurationData); - if (senderInfo == null) - throw new ArgumentNullException(nameof(senderInfo)); + ArgumentNullException.ThrowIfNull(senderInfo); - if (configProviderId == null) - throw new ArgumentNullException(nameof(configProviderId)); + ArgumentNullException.ThrowIfNull(configProviderId); InitialSessionState sessionState = InitialSessionState.CreateDefault2(); // now get all the modules in the specified path and import the same diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index 05448d02d9b..34c10e0a9a0 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -343,10 +343,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] content // to keep the other overload in sync: LengthInBufferCells(string, int) public override int LengthInBufferCells(string source) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return source.Length; } @@ -354,10 +351,7 @@ public override int LengthInBufferCells(string source) // more performant than the default implementation provided by PSHostRawUserInterface public override int LengthInBufferCells(string source, int offset) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(source) || (offset < source.Length), "offset < source.Length"); diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 9feeab94364..e2b5ee8376c 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2178,10 +2178,7 @@ internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } + ArgumentNullException.ThrowIfNull(info); _scriptText = info.GetValue("ScriptText", typeof(string)) as string; if (_scriptText == null) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index bd1eb62f19d..5db4829bb41 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -2777,10 +2777,8 @@ internal static object ForEach(IEnumerator enumerator, object expression, object { Diagnostics.Assert(enumerator != null, "The ForEach() operator should never receive a null enumerator value from the runtime."); Diagnostics.Assert(arguments != null, "The ForEach() operator should never receive a null value for the 'arguments' parameter from the runtime."); - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + + ArgumentNullException.ThrowIfNull(expression); var context = Runspace.DefaultRunspace.ExecutionContext; diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 198f10e45f3..d85b56b4470 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -5933,10 +5933,7 @@ public PSPrimitiveDictionary() public PSPrimitiveDictionary(Hashtable other) : base(StringComparer.OrdinalIgnoreCase) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); foreach (DictionaryEntry entry in other) { diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index dbd80ceaa6f..51d84f8f6ab 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -8146,7 +8146,7 @@ public static partial class AlternateDataStreamUtilities /// The list of streams (and their size) in the file. internal static List GetStreams(string path) { - if (path == null) throw new ArgumentNullException(nameof(path)); + ArgumentNullException.ThrowIfNull(path); List alternateStreams = new List(); @@ -8239,15 +8239,9 @@ internal static FileStream CreateFileStream(string path, string streamName, File /// True if the stream was successfully created, otherwise false. internal static bool TryCreateFileStream(string path, string streamName, FileMode mode, FileAccess access, FileShare share, out FileStream stream) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); - if (streamName == null) - { - throw new ArgumentNullException(nameof(streamName)); - } + ArgumentNullException.ThrowIfNull(streamName); if (mode == FileMode.Append) { @@ -8274,8 +8268,9 @@ internal static bool TryCreateFileStream(string path, string streamName, FileMod /// The name of the alternate data stream to delete. internal static void DeleteFileStream(string path, string streamName) { - if (path == null) throw new ArgumentNullException(nameof(path)); - if (streamName == null) throw new ArgumentNullException(nameof(streamName)); + ArgumentNullException.ThrowIfNull(path); + + ArgumentNullException.ThrowIfNull(streamName); string adjustedStreamName = streamName.Trim(); if (adjustedStreamName.IndexOf(':') != 0) diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 443c2547dfa..10826d25b21 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -1640,8 +1640,7 @@ public TransactedRegistrySecurity GetAccessControl(AccessControlSections include public void SetAccessControl(TransactedRegistrySecurity registrySecurity) { EnsureWriteable(); - if (registrySecurity == null) - throw new ArgumentNullException("registrySecurity"); + ArgumentNullException.ThrowIfNull(registrySecurity); // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. VerifyTransaction(); diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index 2c832a92daf..2f7c991abc4 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -430,10 +430,7 @@ internal static class ProtectedData /// public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { - if (userData == null) - { - throw new ArgumentNullException(nameof(userData)); - } + ArgumentNullException.ThrowIfNull(userData); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); @@ -518,10 +515,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec /// public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { - if (encryptedData == null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } + ArgumentNullException.ThrowIfNull(encryptedData); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 26d1fd7d177..390f66884bf 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -97,10 +97,7 @@ internal static RSA FromCapiPublicKeyBlob(byte[] blob) private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (offset > blob.Length) { @@ -123,10 +120,7 @@ private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (offset > blob.Length) { @@ -175,10 +169,7 @@ private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int internal static byte[] ToCapiPublicKeyBlob(RSA rsa) { - if (rsa == null) - { - throw new ArgumentNullException(nameof(rsa)); - } + ArgumentNullException.ThrowIfNull(rsa); RSAParameters p = rsa.ExportParameters(false); int keyLength = p.Modulus.Length; // in bytes @@ -221,10 +212,7 @@ internal static byte[] ToCapiPublicKeyBlob(RSA rsa) internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (blob.Length < SIMPLEBLOB_HEADER_LEN) { @@ -237,10 +225,7 @@ internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) { - if (encryptedKey == null) - { - throw new ArgumentNullException(nameof(encryptedKey)); - } + ArgumentNullException.ThrowIfNull(encryptedKey); // formulate the PUBLICKEYSTRUCT byte[] blob = new byte[SIMPLEBLOB_HEADER_LEN + encryptedKey.Length]; diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 4c3cbb261e5..cd642683b18 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -30,10 +30,7 @@ public class CmdletInvocationException : RuntimeException internal CmdletInvocationException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord), RetrieveException(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; if (errorRecord.Exception != null) @@ -55,10 +52,7 @@ internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RetrieveMessage(innerException), innerException) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } + ArgumentNullException.ThrowIfNull(innerException); // invocationInfo may be null IContainsErrorRecord icer = innerException as IContainsErrorRecord; @@ -201,10 +195,7 @@ internal CmdletProviderInvocationException( InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } + ArgumentNullException.ThrowIfNull(innerException); _providerInvocationException = innerException; } @@ -464,10 +455,7 @@ public ActionPreferenceStopException() internal ActionPreferenceStopException(ErrorRecord error) : this(RetrieveMessage(error)) { - if (error == null) - { - throw new ArgumentNullException(nameof(error)); - } + ArgumentNullException.ThrowIfNull(error); _errorRecord = error; } @@ -492,10 +480,7 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, string message) : this(invocationInfo, message) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index b333ec25be2..cac77b8576a 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -23,10 +23,7 @@ internal abstract class ObjectReaderBase : PipelineReader, IDisposable /// Thrown if the specified stream is null. protected ObjectReaderBase([In, Out] ObjectStreamBase stream) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream), "stream may not be null"); - } + ArgumentNullException.ThrowIfNull(stream); _stream = stream; } diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index fe7b9c6deac..8f7a86b6801 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -23,10 +23,7 @@ internal class ObjectWriter : PipelineWriter /// Thrown if the specified stream is null. public ObjectWriter([In, Out] ObjectStreamBase stream) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); _stream = stream; #if (false) diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 34ad5c7f4e0..5734fbc6269 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -95,10 +95,7 @@ internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRec : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _message = base.Message; _providerInfo = provider; diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 69cea42b5af..917e04a5e69 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -134,10 +134,7 @@ protected CounterSetRegistrarBase( protected CounterSetRegistrarBase( CounterSetRegistrarBase srcCounterSetRegistrarBase) { - if (srcCounterSetRegistrarBase == null) - { - throw new ArgumentNullException(nameof(srcCounterSetRegistrarBase)); - } + ArgumentNullException.ThrowIfNull(srcCounterSetRegistrarBase); ProviderId = srcCounterSetRegistrarBase.ProviderId; CounterSetId = srcCounterSetRegistrarBase.CounterSetId; @@ -241,10 +238,7 @@ public PSCounterSetRegistrar( PSCounterSetRegistrar srcPSCounterSetRegistrar) : base(srcPSCounterSetRegistrar) { - if (srcPSCounterSetRegistrar == null) - { - throw new ArgumentNullException(nameof(srcPSCounterSetRegistrar)); - } + ArgumentNullException.ThrowIfNull(srcPSCounterSetRegistrar); } #endregion diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 6a0285682df..433d90297ee 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -113,15 +113,9 @@ private sealed class CorrelatedCallback /// public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -135,15 +129,9 @@ public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) /// public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -157,15 +145,9 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) /// public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -184,15 +166,9 @@ public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) /// public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); - if (tracer == null) - { - throw new ArgumentNullException(nameof(tracer)); - } + ArgumentNullException.ThrowIfNull(tracer); this.tracer = tracer; this.parentActivityId = EtwActivity.GetActivityId(); @@ -371,10 +347,7 @@ public void Correlate() /// public CallbackNoParameter Correlate(CallbackNoParameter callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } @@ -386,10 +359,7 @@ public CallbackNoParameter Correlate(CallbackNoParameter callback) /// public CallbackWithState Correlate(CallbackWithState callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } @@ -401,10 +371,7 @@ public CallbackWithState Correlate(CallbackWithState callback) /// public AsyncCallback Correlate(AsyncCallback callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } @@ -417,10 +384,7 @@ public AsyncCallback Correlate(AsyncCallback callback) /// public CallbackWithStateAndArgs Correlate(CallbackWithStateAndArgs callback) { - if (callback == null) - { - throw new ArgumentNullException(nameof(callback)); - } + ArgumentNullException.ThrowIfNull(callback); return new CorrelatedCallback(this, callback).Callback; } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index e093f1de933..d9d082879a6 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -21,10 +21,7 @@ internal class EtwActivityReverterMethodInvoker : public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { - if (eventCorrelator == null) - { - throw new ArgumentNullException(nameof(eventCorrelator)); - } + ArgumentNullException.ThrowIfNull(eventCorrelator); _eventCorrelator = eventCorrelator; _invoker = DoInvoke; diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index a421b918eb8..a6824193bfb 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -64,10 +64,7 @@ public class EtwEventCorrelator : /// during activity correlation. public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transferEvent) { - if (transferProvider == null) - { - throw new ArgumentNullException(nameof(transferProvider)); - } + ArgumentNullException.ThrowIfNull(transferProvider); _transferProvider = transferProvider; _transferEvent = transferEvent; diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index f5c109a1a76..1fdb1319c5c 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -119,10 +119,7 @@ private static void AttemptExecPwshLogin(string[] args) pwshPath = Marshal.PtrToStringAnsi(linkPathPtr, (int)bufSize); Marshal.FreeHGlobal(linkPathPtr); - if (pwshPath == null) - { - throw new ArgumentNullException(nameof(pwshPath)); - } + ArgumentNullException.ThrowIfNull(pwshPath); // exec pwsh ThrowOnFailure("exec", ExecPwshLogin(args, pwshPath, isMacOS: false)); @@ -207,10 +204,7 @@ private static void AttemptExecPwshLogin(string[] args) // Get the pwshPath from exec_path pwshPath = Marshal.PtrToStringAnsi(executablePathPtr); - if (pwshPath == null) - { - throw new ArgumentNullException(nameof(pwshPath)); - } + ArgumentNullException.ThrowIfNull(pwshPath); // exec pwsh ThrowOnFailure("exec", ExecPwshLogin(args, pwshPath, isMacOS: true));