Matthias Burger Matthias Burger - 2 months ago 10
C# Question

assign value to preprocessor directive

Either I did not understand preprocessor directives or they're not working.

I'm trying to write an application for multiple frameworks. (DNX451, DNX46, NETSTANDARD1_5,...)

So I always have to write something like (really simple example, I know I would not need it here)

public class Test
{
#if !(NETSTANDARD1_5 || NETSTANDARD1_6 || NETCOREAPP1_0)
public int? testVar;
#else
public int testVar;
#endif

public string Method()
{
#if !(NETSTANDARD1_5 || NETSTANDARD1_6 || NETCOREAPP1_0)
return (testVar ?? 0).ToString();
#else
return testVar.ToString();
#endif
}
}


so is there a possibility to define a variable? At least per file, so I could say e.g.:

#define NetCore (NETSTANDARD1_5 || NETSTANDARD1_6 || NETCOREAPP1_0)


So I only have to write

public class Test
{
#if !NetCore
public int? testVar;
#else
public int testVar;
#endif
....


would be much less code and I could define it on top of my file.

Or is this simply not possible with preprocessor derectives?

Answer

This seems to work for me (has to be at top of file):

#if (NETSTANDARD1_5 || NETSTANDARD1_6 || NETCOREAPP1_0)
#define NetCore
#endif