Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fiddyschmitt/3493f4006dd6408d3f5caeb77202bcb1 to your computer and use it in GitHub Desktop.
Save fiddyschmitt/3493f4006dd6408d3f5caeb77202bcb1 to your computer and use it in GitHub Desktop.
Enable nullable reference types on old projects
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace EnableNullableReferenceTypes
{
/*
Add the following to the .csproj file:
<PropertyGroup>
...
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<Project>
...
<PropertyGroup>
<PreBuildEvent>"\Desktop\dev\cs\EnableNullableReferenceTypes\EnableNullableReferenceTypes\bin\Debug\EnableNullableReferenceTypes.exe" $(ProjectDir)</PreBuildEvent>
</PropertyGroup>
</Project>
*/
class Program
{
static void Main(string[] args)
{
var files = Directory.EnumerateFiles(args[0], "*.cs", SearchOption.AllDirectories);
files
.ToList()
.ForEach(filename =>
{
if (Path.GetFileName(filename).StartsWith("TemporaryGeneratedFile")) return;
if (Path.GetFileName(filename).Contains(".Designer.cs")) return;
try
{
var firstLine = File.ReadLines(filename).First();
if (!firstLine.Equals("#nullable enable"))
{
var oldText = File.ReadAllText(filename);
var newText = "#nullable enable" + Environment.NewLine + oldText;
File.WriteAllText(filename, newText);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error while processing: {filename}{Environment.NewLine}{Environment.NewLine}{ex}");
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment