Search code examples
c#.netcompilation.net-standard.net-framework-version

Is conditional compilation bad practice when targeting .NET Standard and .NET Framework?


I've always seen conditional compilation as bad practice unless you can't avoid it. AKA #ifdefhell See https://www.cqse.eu/en/news/blog/living-in-the-ifdef-hell/

I'm surprised that Microsoft seems to kind of encourage this without a comment or note that it ought to be avoided. See https://learn.microsoft.com/en-us/dotnet/core/tutorials/libraries#how-to-multitarget

using System;
using System.Text.RegularExpressions;
#if NET40
// This only compiles for the .NET Framework 4 targets
using System.Net;
#else
 // This compiles for all other targets
using System.Net.Http;
using System.Threading.Tasks;
#endif

Should conditional compilation be avoided? Or is it perfectly acceptable to use? To me it's obvious, it's best avoided due to duplicated code, the difficulty in testing and complexity in maintain the code base. However having seen the Microsoft document it's made me question my own assertions.


Solution

  • Well, you probably shouldn't multi-target in the first place, unless you're writing a library that will absolutely (not might, but absolutely!) be used to support legacy projects. Today, there is no reason not to write .Net5 code, unless you're writing UWP/Xamarin apps.

    However, if you are multi-targetting, you need to write code that compiles under all your targets. That involves both #if and MsBuild targetted items, to conditionally include entire source code files.