Home > Back-end >  Only want to return instance of a class if parameters are good
Only want to return instance of a class if parameters are good

Time:01-12

I have a try-catch statement so that if an account is made with -ve money the account should not be made. If no errors are found then the account is made and returned to the Main to be used for MakeWithdrawl(account) and MakeDeposit(account). The problem is that not all code paths return a value. But I only want it to be returned if no error is found so only 1 path SHOULD return a value. I'm fairly new to c# so I'm not sure about different ways to return variables/classes just yet. Any help would be appreciated.

//main
BankAccount account = CreateAccount();
MakeWithdrawl(account);
MakeDeposit(account);

private static BankAccount CreateAccount()
{
    Console.Write("Who is the account named under? : ");
    string name = Console.ReadLine();

    Console.Write("How much would you like to deposit? £");
    decimal amount = Convert.ToDecimal(Console.ReadLine());               

    //Test that the initial balance is positive
    try
    {
        var account = new BankAccount(name, amount);
        Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance}");
        
        return account;
    }
    catch (ArgumentOutOfRangeException e)
    {
        Console.WriteLine("Exception caught creating account with negative balance");
        Console.WriteLine(e.ToString());
    }
}

CodePudding user response:

Refer to the useful comments from Johnathan and Jon. You can add a return statement in your function so that only in the positive case, an account object is returned to the caller, in other cases only a NULL will be returned. Like so,

       private static BankAccount CreateAccount()
       {
            Console.Write("Who is the account named under? : ");
            string name = Console.ReadLine();

            Console.Write("How much would you like to deposit? £");
            decimal amount = Convert.ToDecimal(Console.ReadLine());
                       

            //Test that the initial balance is positive
            try
            {
                var account = new BankAccount(name, amount);
                Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance}");
                return account;
            }
            catch (ArgumentOutOfRangeException e)
            {
                Console.WriteLine("Exception caught creating account with negative balance");
                Console.WriteLine(e.ToString());
            }
           return null;  //added this
        }
  • Related