1

I have a C# library that I want to publish on Nuget. Currently it only builds if I target net8.0-windows because it has <UseWindowsForms>true</UseWindowsForms>.

However, it uses Windows Forms for only some functionality. I would like to conditionally exclude that functionality with #if directives so that I can still have a version of the library with the rest of the functionality that doesn’t rely on Windows Forms, and have that target net8.0 or netstandard2.0.

Is there a way to make UseWindowsForms conditional in this way?

0

1 Answer 1

1

I found the answer. You can still multi-target as usual:

<TargetFrameworks>net8.0-windows;net8.0;netstandard2.0</TargetFrameworks>

but then you have to create a separate PropertyGroup element as follows:

<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0-windows'">
  <UseWindowsForms>true</UseWindowsForms>
  <DefineConstants>USE_WINDOWS_FORMS;$(DefineConstants)</DefineConstants>
</PropertyGroup>

This will apply WinForms only when targeting net8.0-windows. It also defines a compile-time constant so that I can exclude the relevant code from the library:

#if USE_WINDOWS_FORMS
    // WinForms-specific methods go here
#endif
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.