Search code examples
c#visual-studio-code

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

  • 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.