Reputation: 56371
i.e. in PHP, you can build a library of your methods in one file, and error is only given, if there are problems in execution (not in compiler). I wonder if something like that is possible in C#, for example, I could put dedicated methods for both .NET 3.5 and 4.5 in same file:
//myFile.cs
public void mymethod_for_v35(object profile)
public async void mymethod_for_v45(dynamic profile)
so, I could include myfile.cs
in all projects (whether targeting 3.5 or 4.5) and when I am targeting 3.5, in application I will only call first method . However, as 2nd method is for 4.5 (and 3.5 net compilers dont understand that), we still get compilation errors in IDE.
Does there exist any workaround or Flag, to allow the existence of that method (even though it's unsupported in current .NET version of project) ?
Upvotes: 0
Views: 138
Reputation: 1062770
The most convenient way to achieve this is to use a multi-targeted library via the new SDK project syntax (CSP); start by creating a .NET Standard library, then change the <TargetFramework>
to <TargetFrameworks>
, simply semi-colon delimiting the frameworks you need to support separately, for example:
<TargetFrameworks>net40;netstandard1.3;netstandard2.0</TargetFrameworks>
(note that other frameworks will be implicitly supported - so if I consume it from a net462 project, the net40 build will be used)
Now add #if
checks where needed, for example:
#if NET40
...
#endif
or
#if NETSTANDARD1_3
...
#endif
(note that .
is mapped to _
)
This means that the appropriate API surface will be surfaced automatically.
If you need to use different references for different target frameworks, that can also be done in the project file via a condition on an item-group:
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="..."/> <!-- whatever you need here -->
</ItemGroup>
At build, each target-framework will be evaluated (including the conditions) and built separately, then bundled together when creating a nupkg.
Upvotes: 4