Detect C # version at compile time

Is it possible to determine if the current version of C # 6 or higher complies with the preprocessor directive, so at compile time?

I want to do something like this:

var myVar = ...;
string name;

#if VERSION_6_OR_MORE
    name = nameof(myVar);
#else
    name = "myVar";
#endif

I am using Visual Studio 2015 and C # 6, so I can use nameof(). Someone who wants to compile this code may use an older version, where nameof()not.

I want to use the preprocessor directive, so I can save it nameof()in C # 6, but someone who does not use this version can also compile it.

+4
source share
5 answers

nameof() : , , , , , , (, ArgumentNullException(nameof(paramName))) paramName.

, , ( , nameof(), ), nameof().

, #, , : .

+5

. :

  • : CSharp6 CSharp5 ( ).
  • C6 , . , CSHARP6.
  • CSharp5
  • : CSHARP5

:

#if CSHARP6
    name = nameof(myVar);
#else
    name = "myVar";
#endif

.

+2

:

<LangVersion>6</LangVersion>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DefineConstants Condition="'$(LangVersion)' == '6'">DEBUG;TRACE;LANG_VERSION_6</DefineConstants>
+2

# . , undefined, , .

#define//define, #if , .

# ( , foreach), , , , .

script, IMO, # , , .

+1

, ...

- typeof(int).Assembly.ImageRuntimeVersion .

Optional: You can create constants:

<DefineConstants Condition=" '$(LanguageVersion)' == 'v6.0' ">USING_CS6</DefineConstants>
<DefineConstants Condition=" '$(LanguageVersion)' != 'v6.0' ">NOT_USING_CS6</DefineConstants>

I have not tested this though.

-1
source

Source: https://habr.com/ru/post/1657374/


All Articles