Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Preprocesors directive with (c# Version)

Is there any way with a preprocessor to execute code according to the version of C#? Example:

#if CSharpVersion = 7.3
var value = 1;
#endif
like image 341
Julian Ospina Avatar asked Aug 08 '26 05:08

Julian Ospina


1 Answers

One option would be to define the LangVersion explicitly in the Project file and have the constants defined based on it. For example,

<LangVersion>7.3</LangVersion>

and

<DefineConstants Condition="'$(LangVersion)' == '7.3'">DEBUG;TRACE;LANG_VERSION_7_3</DefineConstants>
<DefineConstants Condition="'$(LangVersion)' != '7.3'">DEBUG;TRACE;LANG_VERSION_NOT_7_3</DefineConstants>

Now you could use directives as

#if LANG_VERSION_7_3
            Console.WriteLine("C# 7_3");
#elif LANG_VERSION_NOT_7_3
            Console.WriteLine("Not C# 7_3");
#endif 

Please note the LANG_VERSION would signify the compiler accepts syntax specified version or lower.

like image 152
Anu Viswan Avatar answered Aug 10 '26 18:08

Anu Viswan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!