'Is there a way to compare the value of _MSC_VER in C#? Or is there another way of getting the compiler version in C#?
I'd like to get the version of Visual Studio used to build a C# project without having to resort to C++/CLI. When I use the following in C# the compiler complains.
#if (_MSC_VER == 1500)
// ... Do VC9/Visual Studio 2008 specific stuff
#elif (_MSC_VER == 1600)
// ... Do VC10/Visual Studio 2010 specific stuff
#elif (_MSC_VER == 1700)
// ... Do VC11/Visual Studio 2012 specific stuff
#endif
Is there a way to do this? Thanks
Solution 1:[1]
One alternative would be to define symbols for conditional compilation within the project properties. For instance, you could add, DevEnv17 for VS2022 and DevEnv16 for VS2019.
Ensure you define the right symbols in project properties
<Choose>
<When Condition=" '$(VisualStudioVersion)' == '17.0' ">
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Release|AnyCPU' ">
<DefineConstants>DevEnv17</DefineConstants>
</PropertyGroup>
</When>
<When Condition=" '$(VisualStudioVersion)' == '16.0' ">
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Release|AnyCPU' ">
<DefineConstants>DevEnv16</DefineConstants>
</PropertyGroup>
</When>
</Choose>
Then you could use C# preprocessor directives as below
#if DevEnv17
//Do VS2022 specific stuff
#elif DevEnv16
//Do VS2019 specific stuff
#else
//Do other VS IDE version stuff
#endif
Visual Studio 2022:

Visual Studio 2019:

Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
