Code inspection: Redundant argument passed to caller argument expression parameter
Category: Redundancies in Code
ID: RedundantCallerArgumentExpressionDefaultValue
EditorConfig: resharper_redundant_caller_argument_expression_default_value_highlighting=[error|warning|suggestion|hint|none]
Language: C#, VB.NET
Requires SWA: No
tip
The [CallerArgumentExpression] attribute, introduced in C# 10, allows you to capture the string representation of the expression passed to a method parameter. This can be useful for logging, validation, or debugging purposes.
If you are using an API marked by this attribute, passing the string representation of the corresponding argument with another argument is not necessary. Therefore, ReSharper reports it as redundant and suggests removing it.
In the example below, the attribute is applied to the str
parameter of the Write
method. This means that if you call Write
without specifying an argument for str
, the compiler will automatically use the string representation of the expression provided for num
. Since the argument "a + b"
passed to str
matches the string representation of the expression a + b
passed to num
, the second argument becomes redundant and can be safely removed.
Suboptimal code
using System;using System.Runtime.CompilerServices;class RedundantArgument{ void Write(int num, [CallerArgumentExpression("num")] string str = "") => Console.WriteLine(str); void Test(int a, int b) => Write(a + b, "a + b");}
After the quick-fix
using System;using System.Runtime.CompilerServices;class RedundantArgument{ void Write(int num, [CallerArgumentExpression("num")] string str = "") => Console.WriteLine(str); void Test(int a, int b) => Write(a + b);}