• Status: Solved
• Priority: Medium
• Security: Public
• Views: 170

Call a function

I'm novice in C#. Here is a basic question --
I have 4 variables a, b, c, d in class main(). I want to perform all the mathematical operations on these variables in a function called maths() and get the values back to main. How can I achieve this?

0
praveenuni
2 Solutions

Commented:
Hi

try with

void MyMethod( ref int a, ref int b, ref int c, ref int d )
{
a = 1;
b = 1;
c = 1;
d = 1;
}

int main1()
{
int a = 0;
int b = 0;
int c = 0;
int d = 0;

// Code

MyMethod( ref a, ref b, ref c, ref d );

return 0;
}

Hope this helps

Tincho
0

Independent ConsultantCommented:
This compiles and runs in Visual Studio .NET 2003:

using System;

namespace maths
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static double maths(double a, double b, double c, double d)
{
double total = a + b + c + d;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
double a=1, b=2, c=3, d=4;

//
// TODO: Add code to start application here
//
}
}
}
0

Author Commented:
Thanks for the replies .. one thing I forgot to tell is .. I want to get all the 4 variables to my main function. Becuase in maths function their values will change and I will be getting a,b,c,d with new values.

-- Praveen
0

Commented:
hi Praveen,

what tinchos has mentioned is the right way to do what you want to accomplish. To add to that...you may use either of 'out' or 'ref' method parameters. e.g.

public static Main()
{
int a,b,c,d;
int result1 = Maths(out a,out b, out c, out d);
int result2 = a+b+c+d;
}

private int Maths(out int a, out int b, out int c,out int d)
{
a = 2;
b = 3;
c = 4;
d = 5;
return (a+b+c+d);
}
//result1 and result2 will have same value = 14

the difference between 'out' and 'ref' is that, you have initialize 'ref' variables before passing, while 'out' variables must be assigned some value before returning from the function.
0

Featured Post

Tackle projects and never again get stuck behind a technical roadblock.