Gireesh Sundaram
Gireesh Sundaram

Reputation: 31

How to call a constructor within a method in C#

The scenario is

Hide the constructor of BankAccount. And to allow construction of BankAccount, create a public static method called CreateNewAccount responsible of creating and returning new BankAccount object on request. This method will act as a factory of creating new BankAccounts.

The code i have used is like

private BankAccount()
{
 ///some code here
}

//since the bank acc is protected, this method is used as a factory to create new bank accounts
public static void CreateNewAccount()
{
    Console.WriteLine("\nCreating a new bank account..");
    BankAccount();
}

But this keeps throwing error . I have no idea how to call a constructor within a method in the same class

Upvotes: 3

Views: 2493

Answers (3)

Kristof Claes
Kristof Claes

Reputation: 10941

You should actually create a new instance of BankAccount in that method and return it:

private BankAccount()
{
    ///some code here
}

//since the bank acc is protected, this method is used as a factory to create new bank accounts
public static BankAccount CreateNewAccount()
{
    Console.WriteLine("\nCreating a new bank account..");
    return new BankAccount();
}

Upvotes: 3

bash0r
bash0r

Reputation: 635

Use the 'new' operator:

Foo bar = new Foo();

Upvotes: 0

horgh
horgh

Reputation: 18563

For the method to be factory, it should have the return type of BankAccount. Within that method the private constructor is available and you may use it to create a new instance:

    public class BankAccount
    {
        private BankAccount()
        {
            ///some code here
        }

        public static BankAccount CreateNewAccount()
        {
            Console.WriteLine("\nCreating a new bank account..");
            BankAccount ba = new BankAccount();
            //...
            return ba;
        }
    }

Upvotes: 7

Related Questions