I use C# for .NET. I know how to programmatically detect CLR version of a .NET assembly, but can’t find out how to programmatically detect the C# version in my code. Anyone has idea? TIA.
Asked
Active
Viewed 180 times
-2
-
8This is not possible. The language version does only matter for the compiler at compile time. At runtime, there is no language version. – dymanoid Sep 09 '19 at 15:13
-
8Why are you asking this? This sounds like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - you have a problem X and think Y is the solution. When that fails you ask about Y, not X. There's no language at runtime, only the IL. Do you *really* want to know the language version of the source code that produced your executable even though you can't do anything with it? – Panagiotis Kanavos Sep 09 '19 at 15:14
-
Dupicate of [enter link description here](https://stackoverflow.com/questions/19532942/which-version-of-c-sharp-am-i-using) – hub Sep 09 '19 at 15:15
-
3@hub that answer hasn't worked for the last 7 years - all C# versions up to 7.3 can target any of the 4.x frameworks – Panagiotis Kanavos Sep 09 '19 at 15:18
-
@PanagiotisKanavos: nonetheless, it's as close as the OP's going to get. And in fact, the answer to have the csc.exe compiler print the version is in fact a workable approach. The OP could execute that as a custom build step, parsing the result and embedding that result in their program somehow. Just because C# itself doesn't provide a direct way, doesn't mean it's not possible. – Peter Duniho Sep 09 '19 at 15:59
-
You don't have to target the version of .NET your C# compiler version was released with. You don't even have to target .NET Framework. You could target Mono, Xamarin, .NET Core. – Eric J. Sep 09 '19 at 16:08
1 Answers
7
The C# source code has been translated to IL when the assembly is generated. It's no longer relevant what C# version was used to generate the IL (or indeed, if C# was used), nor is that information stored.
There are some IL features that will not be used by older versions of C# (e.g. support for nullable reference types and async streams). If the IL contains such constructs, you can rule out older C# versions. It's highly non-trivial to make that determination.
Here's a breakdown of the assembly format (click through to the second article in the series). You'll see there's no information describing the language or version that generated the assembly.
https://www.red-gate.com/simple-talk/blogs/anatomy-of-a-net-assembly-pe-headers/

Eric J.
- 147,927
- 63
- 340
- 553