It’s almost two years since I published the post on the Visual Studio IDE information message: “delegate invocation can be simplified.”
It is now the second most visited article on my blog!
While reviewing some error messages in a new MVC project, I recently learnt something equally as simple and eye-opening. This time, the suggestion is:
IDE0018 Variable declaration can be inlined
As a software developer, you’ll likely recognise the following pattern to declare and initialise a variable:
int i;
i = 42;
Equally, you’ll probably know that this can be simplified to a single line:
int i = 42;
I’m a developer who prefers simple, readable code, so I didn’t know where I had seemingly used the first syntax in several places in my project.
I began digging into my code.
The line in question was as follows:
Client clientModel;
if (!IsClientIDValid(environment, dataSource, model.Client.ID, out clientModel))
{
ModelState.AddModelError("model.Client", "The client was not recognised.");
result.IsSuccessful = ModelState.IsValid;
return result;
}
This line declares a new variable called clientModel, of type Client. That variable is passed in to the IsClientIDValid method as an out parameter. If the client ID is valid, the method populates the client model into that variable.
Fairly straight-forward?
How to resolve message IDE0018
Now look what happens to this same code when I implement the suggestion made by Visual Studio:
if (!IsClientIDValid(environment, dataSource, model.Client.ID, out Client clientModel))
{
ModelState.AddModelError("model.Client", "The client was not recognised.");
result.IsSuccessful = ModelState.IsValid;
return result;
}
Notice how the “out” variable declaration is now part of the method call.
I was a bit skeptical that this variable was visible to code following this method call, or if it’s visibility is now limited to the scope of the method call. I needn’t have pondered – it works exactly the same as the previous, 2-line syntax.
Why I love software development
This is what I love about software development – no matter how much I think I know the language, or technology, I can always learn something new. Some little, insignificant way to improve our craft.