Search code examples
c#c-preprocessorconditional-compilation

Preprocessor directives across different files in C#


I know that I can use preprocessor directives in C# to enable/disable compilation of some part of code.

If I define a directive in the same file, it works fine:

#define LINQ_ENABLED
using System;
using System.Collections.Generic;

#if  LINQ_ENABLED
using System.Linq;      
#endif

Now, I'm used in C++ at putting all this configuration directives inside a single header file, and include it in all files where I need such directives.

If I do the same in C# something doesn't work:

//Config.cs
#define LINQ_ENABLED

//MyClass.cs
#define LINQ_ENABLED
using System;
using System.Collections.Generic;

#if  LINQ_ENABLED
using System.Linq;      
#endif

I also tried the following but seems that I can't define a directive inside a namespace:

//Config.cs
namespace Conf{
#define LINQ_ENABLED
}

//MyClass.cs
#define LINQ_ENABLED
using System;
using System.Collections.Generic;
using Conf;
#if  LINQ_ENABLED
using System.Linq;      
#endif
  1. What am I doing wrong?
  2. What's the right way of using preprocessor across different files in C#?
  3. Is there any better way to do that?

Solution

  • In your .csproj there is a section:

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <DefineConstants>TRACE;DEBUG;LINQ</DefineConstants>
      </PropertyGroup>
    </Project>
    

    If you want extra preprocessors you can add them there.

    Or via the properties of the project which will add them there automatically for you. In properties under the Build tab.