I want to migrate my codebase to nullable references. One of migration strategies consists of adding #nullable disable
prefix to all files. How I can do it automatically?
Asked
Active
Viewed 1,632 times
4

Shadow
- 2,089
- 2
- 23
- 45
-
There is a related question about adding a copyright header to all files. The solutions/scripts found there might solve your problem as well: https://stackoverflow.com/q/12199409/87698 – Heinzi Sep 09 '21 at 13:28
-
Note that `file_header_template` won't work -- it doesn't support the `#` character (which gets parsed as a comment), so `#nullable` is right out – canton7 Sep 09 '21 at 13:31
-
The biggest challenge is to not alter encoding on any file – Shadow Sep 09 '21 at 13:34
-
2Go to Replace in Files, check "Use regular expressions", set the "Find" box to `^(?<![.\n])` (which will match the start of a file), and the Replace box to `#nullable disable` (and maybe a trailing newline?). Make sure to use the File types to filter to .cs files. Test carefully first! – canton7 Sep 09 '21 at 13:35
-
@canton7 thanks, that's great! Can you post this as answer so you get all the fame? :) You need to replace with `#nullable disable\n` – Shadow Sep 09 '21 at 18:27
1 Answers
7
One way is to:
- Go to "Replace in Files"
- Check "Use regular expressions"
- Set the "Find" box to
^(?<![\n])
- Set the "Replace" box to
#nullable disable\n
- Set the "File types" to at least contain
*.cs
- Test carefully! I like to do a "Find All" first to make sure the matches are what I want, and use a backup/version control.
^(?<![\n])
is a regex which matches the start of a line (^
) which isn't preceeded by a newline ((?<![\n])
). In other words, the start of the first line of a file.

canton7
- 37,633
- 3
- 64
- 77
-
In case project does not compile after this you may want to use `git clean -fxd` to remove all ignored files and build from scratch. – Shadow Sep 10 '21 at 08:29
-
1If you're on Windows, you might want to consider replacing with `#nullable disable\r\n` instead to avoid the "inconsistent line endings" message box each time you open a code file afterwards. – Heinzi Mar 02 '23 at 16:23
-
We were changing from the opt-in to the opt-out nullable model, so I wanted to only add this to every file that didn't already have the `#nullable enable` directive. This regex seemed to do the trick `^(?<!.|[\n])(?!#nullable enable)`. The regex in this answer also seems to incorrectly include the literal `.` character inside the character set `[.\n]`. Although I'm fairly certain just looking for newline would be enough anyway, `(?<![\n])` – notracs Jun 10 '23 at 04:31