-
Confused
Hey all,
Ive just started learning c#, and im abit confused over the use of methods.
Example is this code:
Code:
class Mdemo
{
public static void Main()
{
Mdemo ca = new Mdemo();
Console.WriteLine("\nResult: {0}", ca.calc());
Console.ReadLine();
}
int calc()
{
int a, b, c;
Console.Write("Enter A: ");
a = Int32.Parse(Console.ReadLine());
Console.Write("Enter B: ");
b = Int32.Parse(Console.ReadLine());
c = a + b;
return c;
}
}
Ok i just made that and it works, but i dont see what the point is in the use of methods? From a C++ view, calc() is just a function, why instead of making an object reference to it, isnt it just called when needed like calc();. I heard something about it being because methods allow multiple instances of the same function to run at the same time, is this correct? I think i understand the code i just dont understand the reason a function has to be referenced to a sub object method to be used. :confused:
Thanks for any tips,
Jack
-
You can make it work without an object reference by making calc() a static function. I don't have my compiler around, but I'm pretty sure this will work:
Code:
public static void Main()
{
Console.WriteLine("\nResult: {0}", calc());
Console.ReadLine();
}
static int calc()
{
int a, b, c;
Console.Write("Enter A: ");
a = Int32.Parse(Console.ReadLine());
Console.Write("Enter B: ");
b = Int32.Parse(Console.ReadLine());
c = a + b;
return c;
}