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

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?

2 Solutions

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

Daniel Van Der WerkenIndependent 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;
                  return total;
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            static void Main(string[] args)
                  double a=1, b=2, c=3, d=4;
                  double answer=0;
                  Console.WriteLine("Answer is {0}", answer);

                  // TODO: Add code to start application here
praveenuniAuthor 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
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.

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

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