Sep 20, 2011

Command line arguments in C#

In C sharp parameter of Main method can have two forms:
Main method without any parameters:

class Program
    {
        static void Main()
        {
        }
    }

Main method with parameters:

class Program
    {
        static void Main(string[] args)
        {
        }
    }

In C#, Main method can have only parameter which array of string. We can pass arguments to the C# program using command prompt. For examples:

C# program to count the total numbers arguments passed through command prompt.

using System;

namespace CommadLineArgs
{
    class Program
    {
        static void Main(string[] args)
        {
            int count;

            count = args.Length;
            Console.WriteLine("Total number of arguments is: {0}", count);
        }
    }
}

In command prompt:
C:\Users\user\Documents\Visual Studio 2010\Projects\ CommadLineArgs\CommadLineArgs\bin\Debug>CommadLineArgs 1 2 3
Total number of arguments is: 3
C:\Users\user\Documents\Visual Studio 2010\Projects\ CommadLineArgs\CommadLineArgs\bin\Debug>CommadLineArgs c c++ java "c sharp"
Total number of arguments is: 4










C# program to print all arguments passed through command prompt.

using System;

namespace CommadLineArgs
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("All arguments are: ");
            foreach (string arg in args)
            {
                Console.WriteLine(arg);
            }
           
        }
    }
}

In command prompt:
C:\Users\user\Documents\Visual Studio 2010\Projects\ CommadLineArgs\CommadLineArgs\bin\Debug>CommadLineArgs c c++ java "c sharp"
All arguments are:
c
c++
java
c sharp













Write a C# program to find the max of three numbers using command line arguments.

using System;

namespace CommadLineArgs
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            int max;

            try
            {
                a = Convert.ToInt32(args[0]);
                b = Convert.ToInt32(args[1]);
                c = Convert.ToInt32(args[2]);

                max = Math.Max(Math.Max(a, b), c);

                Console.WriteLine("Max of given three numbers is: {0}", max);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

In command prompt:
C:\Users\user\Documents\Visual Studio 2010\Projects\ CommadLineArgs\CommadLineArgs\bin\Debug>CommadLineArgs 10 23 7
Max of given three numbers is: 23




No comments:

Post a Comment