2

Is there any compile-time flag in C# that makes it possible to conditionally specify runtime requirements? For example, considering the flag #if DEBUG ... #endif, is it possible to do something similar to:

 #if RUNTIME_LINUX_X64
    // Read file X 
 #endif
 #if RUNTIME_WIN_X64
    // Read file y
 #endif

So that, the correct portion of the code would be compiled based on the -r flag associated with the publish command.

Update: I don't want to use #define xxx and I want to get the target runtime value based on the -r flag only.

Arnold Zahrneinder
  • 4,788
  • 10
  • 40
  • 76
  • You can define yourself debug symbols and use it this way. Also, maybe those files are defined in some environment variables? – Michał Turczyn Jul 28 '22 at 06:30
  • 1
    @MichałTurczyn Right before your comment, I updated the question and mentioned that I would not like to do that as I guessed maybe someone would propose it. – Arnold Zahrneinder Jul 28 '22 at 06:30
  • @MichałTurczyn: Another option would be to use Environment Variable, but for now I would like to investigate what's already available in C# for that purpose. – Arnold Zahrneinder Jul 28 '22 at 06:32
  • This is a bit tangential, I'm just thinking what should happen in `dotnet build`, do you specify the RID always or will you always have to think of an else case when RID isn't specified and whether that's fine for you? – Zdeněk Jelínek Jul 28 '22 at 06:35
  • @ZdeněkJelínek: the runtime is always specified, and I am creating a generic tool that can run in any CICD pipeline whether relying on linux containers or windows containers. So I want to minimize the need for any potential configuration. And I'd like to know if I can do this at compile time. – Arnold Zahrneinder Jul 28 '22 at 06:37
  • The #if directives are compile time only, i.e. you can control what gets compiled depending the compile environment. If you want to enter different code pathes depending on the OS at runtime use `Environment.OSVersion.Platform`. As the value would be a constant at runtime, the JITer should remove any code pathes that don’t match your OS. – ckuri Jul 28 '22 at 07:15

1 Answers1

3

You can define constants by providing DefineConstants property:

dotnet build -p:DefineConstants=SOME_PREPROCESSOR_SYMBOL

But in this particular case probably you can just use Environment.OSVersion or RuntimeInformation.IsOSPlatform check.

Also check out:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • `Environment.OSVersion` and `RuntimeInformation.IsOSPlatform` are dynamic ways to identify `OS` in runtime. I want to manually define it to the build at compile time. `DefineConstants` seems to be a nice way to do this. – Arnold Zahrneinder Jul 28 '22 at 09:27