Reputation: 23
How to pass inputted values of user in main method to my Add() method parameter? And also how to output the result to my Add() method?
int Add(int a,int b)
{
return a + b;
}
static void Main(string[] args)
{
int num1;
int num2;
Console.WriteLine("Input any whole number: ");
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Input any whole number again: ");
num2 = int.Parse(Console.ReadLine());
}
Upvotes: 1
Views: 710
Reputation: 13676
A more object-oriented approach would be to put it into a new class and use it:
public class MyCalculator
{
public int Add(int a,int b)
{
return a + b;
}
}
static void Main(string[] args)
{
...
var calculator = new MyCalculator();
var res = calculator.Add(num1, num2);
Console.WriteLine(res);
}
However if we think about it a bit more it is not that obvious. For example class Math
in .Net
is static so specifically for objects like calculator you might want to make them static as well:
public static class MyCalculator
{
public static int Add(int a,int b)
{
return a + b;
}
}
And use it like this MyCalculator.Add(x1, x2);
Upvotes: 4
Reputation:
You should make your Add
method static
here, because it should be callable from the static Main
method.
public static int Add(int a, int b)
{
return a + b;
}
Then you will need to save the result from an Add
method call in a variable (result
for example) and output it to the console. You could add these lines to the bottom of your Main
method:
int result = Add(num1, num2);
Console.WriteLine(result);
Console.ReadKey();
Upvotes: 7