Is it possible to pass an integer value as method arguments in a C # console application
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 to share
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 to share