ReSharper 2023.3 Help

Code Inspection: Parameter hides primary constructor parameter

Initializing a using variable with an object initializer might be a problem if an exception is thrown during the initialization. This is possible because the compiler creates and initializes the object before the execution enters the using clause. If an exception is thrown during the initialization, the program will never enter the using clause and the object will not be disposed.

In the example below, the parameter str of the Print() method has the same name as the primary constructor parameter of the MySample class, but it is still clear that Console.WriteLine(str); will print out two.

Now imagine that MySample and Print() are lengthy declarations with multiple parameters. In this case, readers of the code may miss the str parameter in the method and assume that Console.WriteLine(str); will print out one, received during the object creation.

To avoid confusion and potential errors, rename the method parameter.

public class MyTest { public MyTest() { var sample = new MySample("one"); sample.Print("two"); } } public class MySample(string str) { public void Print(string str) { Console.WriteLine(str); } }
Last modified: 15 December 2023