Is it possible to pass an integer value as method arguments in a C # console application

In my code

static void Main(string[] args)
{

}

      

what i want to pass integer value in args method

static void Main(int? args)
{

}

      

+3


source to share


3 answers


You cannot - you can only accept strings. However, you can parse these strings as integers. For example:

static void Main(string[] args)
{
    int[] intArgs = args.Select(int.Parse).ToArray();
    // ...
}

      



Note that this will throw an exception if any of the arguments are not actually an integer. If you want a more user-friendly message, you will need to use int.TryParse

for example

static void Main(string[] args)
{
    int[] intArgs = new int[args.Length];
    for (int i = 0; i < args.Length; i++)
    {
        if (!int.TryParse(args[i], out intArgs[i]))
        {
            Console.WriteLine($"All parameters must be integers. Could not convert {args[i]}");
            return;
        }
    }
}

      

+11


source


Hopefully this is not possible, but you can get the value as a string array as you already get and parse them to get the integer you want.



public static int[] intArgs;
static void Main(string[] args)
{
     intArgs = args.Select(x=> int.Parse(x)).ToArray();
}

      

+1


source


When you use the console, when you type "123" it is line 123 not an integer value 123. So static void is Main (int[] args)

not an option.

Check MSDN documentation: https://msdn.microsoft.com/en-us/library/cb20e19t(VS.71).aspx

However, you can split strings by int. For example:

var intValue = int.Parse(args[0]);

      

0


source







All Articles