Until C# 9.0, It was all about the Main() method where program control start and ends. With C# 9.0, you don’t need to mention the Main() method or Class definition explicitly using Top-Level Statement. Then how do you pass command-line arguments for your program? especially when you are running it from Visual Studio. In this post let us have a look at how we can pass command line arguments in Visual Studio for C# 9.0 Top Level Statement.
Typical C# Console Vs Top-Level Statement in C# 9.0
A typical Hello World Console Application for C# looks as below
using System;
namespace TopLevelStatementCsharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
With Top-Level Statement in C# 9.0, you can achieve the same using just following line of code.
System.Console.WriteLine("Hello World!");
Which will produce the same output as previous code block.
Command Line Arguments with Visual Studio
You can pass the parameter for the top-level statement along with multiple arguments.
System.Console.WriteLine($"Hello {args?[0]}");
In Visual Studio you can set the parameter from the debug tab as “Application Argument” .
Once this is set, you can run and test it out.
Read : How to Pass Command Line Arguments using Visual Studio ?
Looking for mentorship: Connect 1:1 with Abhijit
would be happy to connect and mentor you for your personal and professional growth. I can provide you career guidance, share my thoughts for any interview preparation, or ask me anything related to choosing a technology platform, guide you in writing your first book, help you in public speaking, or starting your own blog.
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #3250
Pingback: Dew Drop – June 11, 2021 (#3463) – Morning Dew by Alvin Ashcraft