Home > Mobile >  generating .cs files with lower language version
generating .cs files with lower language version

Time:12-07

Background

I'm developing an extension code for ancient dotnet system.

The system requires all .cs files to be in C# 6.0 Language version. Said ancient system reads .cs files at runtime. Therefore, the only thing I can do is to prepare 'raw' .cs files as-is, not as compiled .dll files.

Question

Is there a way to write .cs in up-to-date version, and then simply 'translate' them into older version of them?

Note that TargetFramework option does not work, as I'm not doing any compiling. I'm only trying to transform .cs into another .cs.

Example

namespace Test;

// code...

This file scoped namespace works in modern C# 10.0, but it fails if I try to feed it into an older system. As this feature does not exist in C# 6.0.

So, It would be better if I could:

////////// source.cs
namespace Test;

public class Class {}
//////////

// some magic happens...

////////// dist.cs
namespace Test {
    public class Class {}
}
//////////

CodePudding user response:

To generate a .cs file with a lower language version, you can specify the /langversion flag when using the csc compiler. For example, to generate a .cs file with C# 6.0 language support, you would use the following command:

csc /langversion:6 MyFile.cs

Alternatively, you can specify the language version in your project file, if you are using one. For example, in a project file called MyProject.csproj, you can add the following property to set the language version to C# 6.0:

<PropertyGroup>
 <LangVersion>6</LangVersion>
</PropertyGroup>

Keep in mind that using a lower language version will restrict you to using only the features and syntax that are available in that version. You may need to modify your code to use older language constructs if you want to use a lower language version.

CodePudding user response:

Compile your code with the version of your choice, then decompile it with ILSpy while setting the version of language to C# 6.0.

  •  Tags:  
  • c#
  • Related