I want to modify how some code in Visual Studio 22 is generated.
For instance, in methods I can generate null check on using the Add null check
(MS docs link) for arguments in the following way.
public void MyMethod(object parameter)
{
if (object is null)
{
throw new ArgumentNullException(nameof(parameter));
}
// rest of the method
// ...
}
What I would like to be generated is this:
public void MyMethod(object parameter)
{
if (object is null) throw new ArgumentNullException(nameof(parameter));
// rest of the method
// ...
}
I was looking at code snippet settings and refactoring settings but I can not find the Add null check
option anywhere. Let alone change it.
The best option I came up with is to create a code snippet (MS docs link) but that does not serve my purpose fully.
Is there an option I can modify to say how is the code generated?
CodePudding user response:
Rewriting an answer by canton7 from the comments:
The Add null check is not generated by any code snippet. Rather it is based on the standard analyzer infrastructure (defined here and seen here). This means it is just a semantically generated if
statement with a throw
inside of it. Then based on your .editorconfig (or defaults if not specified) it formates the code accordingly.
One is left with the following options:
- Edit the .editorconfig file to make the code format as pleased. Note that this approach applies globally.
- Wait for the C# 11
!!
syntax. - Write your own analyzer and code fix (tutorial).
- Edit it by hand :).