/ PROGRAMMINGVISUAL-STUDIOSATIRE

Tired of other developers? #ifdef your code with your Windows username

We all know other developers write bad code. My code is the best.

So what if I could only run my code and not worry about other people’s code?

Introducing misused conditional compilation symbols!

John likes simple variable names and short code. Jake believes in descriptive names and leveraging existing libraries like LINQ. Who is right? Both of them!

Console.WriteLine(Multiply(6, 4)); // 24

#if john
int Multiply(int a, int b)
{
    return a * b;
}
#endif

#if jake
int Multiply(int multiplier, int multiplicand)
{
    return Enumerable.Repeat(multiplicand, multiplier).Sum();
}
#endif

If John compiles this with msbuild /p:DefineConstants="john", Jake’s code will not be included in the compilation process, because the if won’t trigger. More information on how preprocessor symbols work in C# here. Other languages also have preprocessor directives and symbols, so look up your own.

We can define symbols in .csproj project files like this:

<PropertyGroup>
  <DefineConstants>john;jake</DefineConstants>
</PropertyGroup>

Multiple usernames won’t work - the compiler complains two methods called Multiply are defined. This is because now both #if checks are true. We can simplify and use MSBuild’s built-in variables. No need to have each developer change the .csproj on their end.

<PropertyGroup>
  <DefineConstants>$(USERNAME)</DefineConstants>
</PropertyGroup>

Now whichever Windows user does the compilation, either manually through a terminal or inside Visual Studio, will have their code run instead of their rivals’. It’s easier to find bugs this way too, you always know who’s responsible.

You can also have different symbols in Debug and Release, in case you want only one person’s changes to be in the official Release build.

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
  <DefineConstants>$(DefineConstants);john</DefineConstants>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
  <DefineConstants>$(DefineConstants);$(USERNAME)</DefineConstants>
</PropertyGroup>

MSBuild supports other variables like $(USERDOMAIN) and $(USERDNSDOMAIN).

You can also add your symbols in Visual Studio: Image of the Build tab in Visual Studio showing conditional compilation symbols

Let me know how this works in other environments like Rider or under Linux and MacOS.