- 1
How can I make a method use values of another method
5 Respostas
- 1
Pass the method through as an argument in the second method, which assigns it's return value to a variable used in the second method. Alternatively you could have variables within Main hold the return values from the previous method having already ran, and pass the variables from Main as arguments in the second method.
Here's an example:
static int Sum (int a, int b)
{
return a + b;
}
static int MultiplyAfterSum (int a, int b, int c)
{
return Sum (a, b) * c;
}
Now in Main you could use say...
Console.WriteLine ( MultiplyAfterSum (2, 3, 4) );
... and it would print the answer of the sum of 2 and 3, multiplied by 4.
Hope this formats correctly
- 1
I should also note, that I simply used the sum method within the other method return field, which is going to have the same effect as using the other two described...methods.
- 1
The common pattern is by assign the value into a variable, then use this variable as normal.
But if you want to get it from the method of same class, you can use this.Method(), where method should return a value;
i.e. (getting values inside the same class)
class Name {
public string First { get; set; }
public string Last { get; set; }
public string Full () {
return this.First() + " " + this.Last();
}
using:
Name myName = new Name();
myName.First = "Ednei";
myName.Last = "Almeida";
Console.WriteLine(myName.Full()); // prints Ednei Almeida
- 1
Thanks, it was very useful. I used the solution by Ednei, and it worked. Thanks
- 1
You could also use an 'out' parameter defined in your method. This works best if performing an action where the method does not contain an object whose values you could be using instead of the 'out' variable. Keep in mind that an 'out' variable allows you to return more than one value in a method. So for example you could have a method that takes an 'out' parameter of 1 and the method itself could return 2, so when you execute the method you can store both the returned value and out parameters in two different int variables.