简体   繁体   中英

c# passing Parameters values from function to other function

are there any way to get the values from Parameters in "functionone" and calculate it in the "functiontwo" without writing that again that's a small code for example what i mean

public void functionone(int x, int y)
{

   x = 1;
   y = 2;

}

public void functiontwo(int a , int b )
{
   a=x+y;
   b=x-y;

   Console.WriteLine(a);
   Console.WriteLine(b);


}

You are implementing functionone wrongly I guess doing this: public void functionone(int x, int y) { x = 1; y = 2; } is normally not the way to pass parameters and change its values in the method, or saying in another way, x and y should be holding the values you pass as parameters, and no getting assigned inside the method..

define a global x and global y, then you can access to it everywhere in that scope..

Example:

class Abc{
    int globalX;
    int globalY;
....
public void functionone(int x, int y)
{
   globalX = 1 + x;
   globalY = 2 + y;
}

public void functiontwo(int a , int b )
{
   a=globalX + globalY;
   b=globalX - globalY;

   Console.WriteLine(a);
   Console.WriteLine(b);
}

}

To explain my comment :

int globalX;
int globalY;

public void functionone(ref int x, ref int y)
{
    x = 1;
    y = 2;
}

public void functiontwo(ref int a , ref int b)
{
    a = globalX + globalY;
    b = globalX - globalY;

    Console.WriteLine(a);
    Console.WriteLine(b);
}


// in main

functionone(ref globalX, ref globalY);
// globalX and globalY are now 1 and 2

functiontwo(ref a, ref b);
// a = 3 and b = -1  ->  'globalX +/- globalY'

This way you can set the values of any variables you pass to functionone or functiontwo .

However it doesn't look good and in my opinion it's not a good code. Your concept seems wrong, so maybe you can post a description of the problem you encountered?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM