Hello everyone,
can anyone please tell me how can we write and call function in C# console application through command prompt
For ex. My consoleapplication1 is having function add
so in command prompt i can run it as
consoleapplication1/add
and it's run successfully.
Loading

Michal HabalcikRank #902 · 2.3K reputationPosted Dec 23, 2014, 9:32 PM EST
the main method's arguments represent command prompt arguments
static void Main(string[] args)
so you need to handle input in your main method, something like this:
foreach (var arg in args)
{
if (arg == "add")
call your add method here;
}
afterwards, you can call it from command prompt like
consoleapplication1 add
More info on MSDN
shubhangi d13 reputationPosted Dec 23, 2014, 9:53 PM EST
how can we take input then
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 23, 2014, 9:57 PM EST
If you add the above code in your Main method, you can call the Add function from command prompt by typing:
consoleapplication1 add
shubhangi d13 reputationPosted Dec 23, 2014, 10:00 PM EST
It's not working
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 23, 2014, 10:02 PM EST
can you paste your code snippet here?
shubhangi d13 reputationPosted Dec 23, 2014, 10:05 PM EST
{
if (args.Length == 0)
{
foreach (var arg in args)
{
if (arg == "add")
Add();
if (arg == "deduct")
Deduct();
}
}
Console.ReadLine();
}
public static int Add()
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
c = a + b;
Console.WriteLine("a + b = {0}", c);
Console.ReadLine();
Console.ReadLine();
return c;
}
public static int Deduct()
{
int a;
int b;
int c;
Console.WriteLine("Enter value of 'a':");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value of 'b':");
b = Convert.ToInt32(Console.ReadLine());
c = a - b;
Console.WriteLine("a - b = {0}", c);
Console.ReadLine();
Console.ReadLine();
return c;
}
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 23, 2014, 10:06 PM EST
I had updated my post and you didn't realize it.
shubhangi d13 reputationPosted Dec 23, 2014, 10:52 PM EST
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 23, 2014, 10:54 PM EST
shubhangi d13 reputationPosted Dec 23, 2014, 11:00 PM EST
ConsoleApplication1/add
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 23, 2014, 11:02 PM EST
a suggest putting a breakpoint or writing the content of that array to the console to check what is actually inside.
foreach (var arg in args)
{
Console.WriteLine(arg);
}
shubhangi d13 reputationPosted Dec 23, 2014, 11:07 PM EST
if (Message != "")
{
if (Message == "add")
Add();
if (Message == "deduct")
Deduct();
}
It's work now
thanx a lot