Hi @zequion , Welcome to Microsoft Q&A,
Make sure that the correct compilation symbol definitions are included in the project file.
.NET Framework 4.8 project file (.csproj):
xmlCopy code
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
.NET 8 project file (.csproj):
xmlCopy code
<Project Sdk="Microsoft.NET.Sdk">
Create a class library project and use conditional compilation directives in your code. This class library will generate DLLs containing code for different frameworks.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48;net8.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net48'">
<DefineConstants>NET48</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
<DefineConstants>NET8</DefineConstants>
</PropertyGroup>
</Project>
Use #if directives in shared class library projects to distinguish code from different frameworks.
using System;
public class FrameworkSpecificClass
{
public void FrameworkSpecificMethod()
{
#if NET48
Console.WriteLine("Running on .NET Framework 4.8");
#elif NET8
Console.WriteLine("Running on .NET 8");
#else
Console.WriteLine("Running on an unknown framework");
#endif
}
public void SpecificMethod()
{
#if NET48
SpecificMethodForNet48();
#elif NET8
SpecificMethodForNet8();
#endif
}
#if NET48
private void SpecificMethodForNet48()
{
Console.WriteLine("Specific method for .NET Framework 4.8");
}
#elif NET8
private void SpecificMethodForNet8()
{
Console.WriteLine("Specific method for .NET 8");
}
#endif
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.