Reputation: 17
I am writing a bit of a dungeon crawler as I learn my way through c#. I am using visual studio and the application is a "Console App (.NET Framework)". My problem is that I use a method (a fighting sequence) that can be called from the Main method. However I want it to be able to change the balance variable in my Main method.
static void Main(string[] args )
{
int balance = 0;
battle(balance);
}
static void battle(int balance);
{
balance = balance + 30;
}
// I want the balance in the battle to change the balance in the Main.
Upvotes: 0
Views: 196
Reputation: 127543
While using ref
is one possible way to do this (see Kibbee's answer for a example), another way that will help you scale up in the future is put all of your variables that relate to the player in to a Player
class that can be passed in to methods.
This allows more variables to be added in the future and you don't need to modify the functions to add the extra parameter.
class Player
{
int Health {get; set;}
int Balance {get; set;}
}
static void Main(string[] args )
{
Player player = new Player();
player.Balance = 0;
player.Health = 50;
Battle(player);
}
static void Battle(Player player);
{
player.Balance = player.Balance + 30;
player.Health = player.Health - 5;
}
This also lets you expand in the future if you want your game to have more than one person in the party.
static void Main(string[] args )
{
Player player1 = new Player();
player1.Balance = 0;
player1.Health = 50;
Player player2 = new Player();
player2.Balance = 500;
player2.Health = 100;
Battle(player1);
CastHeal(player1, player2)
}
Upvotes: 1
Reputation: 11
You can return the value from the method battle(int balance)
class Program
{
static void Main(string[] args)
{
int balance = 0;
balance = battle(balance);
}
private static int battle(int balance)
{
balance = balance + 30;
return balance;
}
}
Or you can create a class-scope variable
class Program
{
private static int balance;
static void Main(string[] args)
{
battle(balance);
}
private static void battle(int balance)
{
balance = balance + 30;
}
}
Upvotes: 1
Reputation: 66112
You need to pass the value by reference. To pass the value by reference, change the following line:
static void battle(int balance)
to
static void battle(ref int balance)
Then you can call the function as follows:
battle(ref balance);
Alternatively, you can just change your function to return the balance as a result, as follows
static void Main(string[] args )
{
int balance = 0;
balance += battle();
}
static int battle();
{
return 30;
}
I used 30 because this is all your original function does.
Upvotes: 3