'How to fix C# Warning CA1416 in vscode?

I'm just starting to learn C# following Brackeys on Youtube. Upon writing along I get this problem pop up in vscode:

{
"resource": "/d:/OneDrive/Programming/Youtube/brackeys/How To Program In C#/Basics/Program.cs",
"owner": "msCompile",
"code": "CA1416",
"severity": 4,
"message": "This call site is reachable on all platforms. 'Console.WindowHeight.set' is only supported on: 'windows'. [D:\\OneDrive\\Programming\\Youtube\\brackeys\\How To Program In C#\\Basics\\Basics.csproj]",
"startLineNumber": 11,
"startColumn": 13,
"endLineNumber": 11,
"endColumn": 13
}

I have found this Microsoft article talking about this Warning, but I do not understand the solution if it's actually that :(...

I have a simple program, just learning about Console class changing the terminal height and font color etc:

    using System;
    
    namespace Basics
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.Title = "Skynet";
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WindowHeight = 40;
    
                Console.WriteLine();
    
                Console.ReadKey();
    
            }
        }
    }

Does anyone have an idea on how to tackle this problem?



Solution 1:[1]

So the error is about this line:

Console.WindowHeight = 40;

You try to set the Window Height, which is a method decorated with the [SupportedOSPlatform("windows")] attribute.

In order to tell the application to only execute this line when in Windows wrap the method.

if (OperatingSystem.IsWindows())
{
  Console.WindowHeight = 40;
}

The compiler will recognize this and stop throwing the remark.

Solution 2:[2]

If you know you're only developing for Windows, you can mark your code as such:

using System.Runtime.Versioning;

[SupportedOSPlatform("windows")]
class Program
{
    ...
}

The advantage of this approach is you avoid peppering your code with IF statements to check the OS version.

You can also mark specific methods this way if you don't want it to apply to the whole class.

Also see this answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Verstraete
Solution 2