C
C#3mo ago
Shrow

Trying to get a method to work

I'm very new to code. On the first image you'll see from line 58 to 62 the method I've declared. On line 94 you'll see where the method is being used. Unfortunately the line appears to be ignored. Why is that? I could just write Monster1.hp -= attroll; but I'm trying to learn methods and be more object oriented.
No description
No description
3 Replies
mtreit
mtreit3mo ago
You are not assigning the return value of the method to a variable, so it just throws the result away into the ether. You might also be getting confused because value types (like int) are passed by value not by reference, so when you pass an integer into a method it makes a copy that is only valid for the length of time that method is running. It doesn't mutate the value stored in the original variable you passed in. You can actually pass in method parameters using the ref keyword that mutate the original variable that was passed in. However, this is usually only used for advanced scenarios and is best avoided in almost all normal cases.
MODiX
MODiX3mo ago
mtreit
REPL Result: Success
var a = 1;
var b = 2;

var result = AddTwoNumbers(a, b);
Console.WriteLine($"value of 'a' after call: {a}; value of 'b' after call: {b}; method return value: {result}");

result = AddTwoNumbersByRef(ref a, b);
Console.WriteLine($"value of 'a' after call: {a}; value of 'b' after call: {b}; method return value: {result}");

int AddTwoNumbers(int x, int y)
{
x = x + y;
return x;
}

int AddTwoNumbersByRef(ref int x, int y)
{
x = x + y;
return x;
}
var a = 1;
var b = 2;

var result = AddTwoNumbers(a, b);
Console.WriteLine($"value of 'a' after call: {a}; value of 'b' after call: {b}; method return value: {result}");

result = AddTwoNumbersByRef(ref a, b);
Console.WriteLine($"value of 'a' after call: {a}; value of 'b' after call: {b}; method return value: {result}");

int AddTwoNumbers(int x, int y)
{
x = x + y;
return x;
}

int AddTwoNumbersByRef(ref int x, int y)
{
x = x + y;
return x;
}
Console Output
value of 'a' after call: 1; value of 'b' after call: 2; method return value: 3
value of 'a' after call: 3; value of 'b' after call: 2; method return value: 3
value of 'a' after call: 1; value of 'b' after call: 2; method return value: 3
value of 'a' after call: 3; value of 'b' after call: 2; method return value: 3
Compile: 559.638ms | Execution: 38.005ms | React with ❌ to remove this embed.
Shrow
Shrow3mo ago
Thank you for the help.
Want results from more Discord servers?
Add your server