World’s smallest C# program (featuring cheating)
When I read World’s Smallest C# Program (featuring `N`) I was so intrigued. I had to give it a shot myself.
Sadly, as I was reading the article, the rules killed all my ideas. But I went ahead anyway. My smallest C# program, that even(!) does something, is this.
Yep, it’s an empty file. In fact, it can be no file whatsoever. From the title of this post, you probably already know I’m cheating. What I did, is (ab)use MSBuild to generate a file and add it into compilation.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<ProgramText>
<![CDATA[
namespace Mini%3B
public class Program
{
public static void Main()
{
System.Console.WriteLine("Mini!")%3B
}
}
]]>
</ProgramText>
</PropertyGroup>
<Target Name="AddGeneratedProgram" BeforeTargets="BeforeCompile;CoreCompile" Inputs="$(MSBuildAllProjects)" Outputs="$(IntermediateOutputPath)GeneratedProgram.cs">
<PropertyGroup>
<GeneratedProgramPath>$(IntermediateOutputPath)GeneratedProgram.cs</GeneratedProgramPath>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(GeneratedProgramPath)" />
<FileWrites Include="$(GeneratedProgramPath)" />
</ItemGroup>
<WriteLinesToFile Lines="$(ProgramText)" File="$(GeneratedProgramPath)" WriteOnlyWhenDifferent="true" Overwrite="true" />
</Target>
</Project>
I took the inspiration from this and only slightly modified it.
And although it’s cheating in this “competition”, it’s good to know I can rather easily generate (C#) files from MSBuild and include some values of variables (like version for example).