1

I am currently building a .NET assembly that should work in .NET 4.5 and at least two .NET Core versions (.NET Core 2.1 and .NET Core 3.0).

I am using conditional compilation like so:

#if NET45
        //Use as System.Web.HttpContext
        isHttps = context.Request.IsSecureConnection;
        IPAddress fromIp = IPAddress.Parse(context.Request.UserHostAddress);
        string path = context.Request.Path;
#elif NETCOREAPP2_1
        //Use as Microsoft.AspNetCore.Http.HttpContext
        isHttps = context.Request.IsHttps;
        IPAddress fromIp = context.Request.HttpContext.Request.HttpContext.Connection.RemoteIpAddress;
        string path = context.Request.Path;
#elif NETCOREAPP3_0
        //Use as Microsoft.AspNetCore.Http.HttpContext
        isHttps = context.Request.IsHttps;
        IPAddress fromIp = context.Request.HttpContext.Request.HttpContext.Connection.RemoteIpAddress;
        string path = context.Request.Path;
#endif

Since the code for NETCOREAPP2_1 and NETCOREAPP3_0 is the same I wonder wheter I could use something like:

#if NET45
        //...
#elif NETCOREAPP2_1 [OR] NETCOREAPP3_0
        //...
#endif    

However, this syntax does not work.

Is there valid syntax to have an OR operator in conditional compilation like this?

Note: Since this involves the ASP.NET request pipeline, I guess .NET Standard is not an option. You may want to have a look at the code in time: https://github.com/suterma/SqlSyringe/blob/f7df15e2c40a591b8cea24389a1ba8282eb02f6c/SqlSyringe/Syringe.cs

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Marcel
  • 15,039
  • 20
  • 92
  • 150
  • Yes. Check https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if – Gaurang Dave Oct 30 '19 at 06:59
  • 1
    As you are targeting 2 versions of .NET Core and want _the same code for both of them_ you could simplify this to `#elif NETCOREAPP` - see https://stackoverflow.com/a/57031308/397817 – Stephen Kennedy Nov 05 '19 at 14:26

1 Answers1

8

Yes there is. It's the same as in a standard if:

#if NET45
    // ...
#elif (NETCOREAPP2_1 || NETCOREAPP3_0)
    // ...
#endif

More here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if

MindSwipe
  • 7,193
  • 24
  • 47