using System; class SayHello { public static void Main(string[] args) { if (args.Length > 0) { foreach (string arg in args) { if (arg.Equals("/help")) Console.WriteLine("Run this program as follows: sayhello.exe [name1] "); else Console.WriteLine("Hello " + "{0}", arg); } } else Console.WriteLine("For help, run sayhello.exe /help"); } }
Return different value to the operating system based on the argument length
using System; class SayHello { public static int Main(string[] args) { if (args.Length > 0) { foreach (string arg in args) { if (arg.Equals("/help")) { Console.WriteLine("Run this program as follows:" + "sayhello.exe [name1] "); return (1); } else Console.WriteLine("Hello " + "{0}", arg); } return (0); } else Console.WriteLine("For help, run sayhello.exe /help"); return (2); } }
Using command-line arguments to initialize an array.
using System;
public class InitArray
{
public static void Main( string[] args )
{
int arrayLength = Convert.ToInt32( args[ 0 ] );
int[] array = new int[ arrayLength ]; // create array
int initialValue = Convert.ToInt32( args[ 1 ] );
int increment = Convert.ToInt32( args[ 2 ] );
for ( int counter = 0; counter < array.Length; counter++ ) array[ counter ] = initialValue + increment * counter; Console.WriteLine( "{0}{1,8}", "Index", "Value" ); for ( int counter = 0; counter < array.Length; counter++ ) Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] ); } } [/csharp]
The Main Function
using System; public class TheMainFunction { public static void Main() { Console.WriteLine("Hello, Universe!"); } }
The Main Function:Returning an Int Status
using System; public class ReturninganIntStatus { public static int Main() { Console.WriteLine("Hello, Universe!"); return(0); } }
The Main Function:Command-Line Parameters
using System; public class CommandLineParameters { public static void Main(string[] args) { foreach (string arg in args) Console.WriteLine("Arg: {0}", arg); } }
Main Function: Multiple Mains
// error using System; class Complex { static int Main() { // test code here Console.WriteLine("Console: Passed"); return(0); } } public class TheMainFunctionMultipleMains { public static void Main(string[] args) { foreach (string arg in args) Console.WriteLine(arg); } }