0

Calling an object's method outside of Main()

Using the bank account example in the Classes section of the C# tutorial, I created a public class BankAccount{}. In my Main method I created an object BankAccount ba1 = new BankAccount. This object has a GetBalance(); method which returns the balance. I can call it in the Main() method but why can't I call it in a different method? For example in a Menu() method I created which Main calls when the user has to make a selection. ba1 gets a red underline and says it "does not exist in the current context"

25th Jan 2019, 4:56 AM
JPressley
JPressley - avatar
2 Answers
+ 2
Hello! As Hatsy Rei already told you, you need to pass the object as argument to the menu function in order to be able to call the BankAccount`s method from there! This is the example from the C# course, I modified it to be as you described; class BankAccount { private double balance=0; public void Deposit(double n) { balance += n; } public void Withdraw(double n) { balance -= n; } public double GetBalance() { return balance; } } class Program { //The Menu function takes a BankAccount object as argument static void Menu(BankAccount bnk) { //Since we are passing the reference to the BankAccount object we can call its method from this function Console.WriteLine(bnk.GetBalance()); } static void Main(string[] args) { BankAccount b = new BankAccount(); b.Deposit(199); b.Withdraw(42); //We pass the object b to the Menu function Menu(b); } //Output: 157 If you want to call the BankAccount method from the Menu function but without passing an object as argument then you should declare a new object inside that function: static void Menu() { BankAccount b = new BankAccount(); b.GetBalance(); }
25th Jan 2019, 7:38 AM
Sekiro
Sekiro - avatar
+ 3
Your object was created in Main, and probably does not exist in Menu. To call the method using an object which was created in Main, you probably need to pass the object to Menu as a parameter. Note: If you can attach your code, we can get rid of the uncertainty surrounding this issue, and others should be able to help you easier.
25th Jan 2019, 5:10 AM
Hatsy Rei
Hatsy Rei - avatar