BizC#

Being Object Stingy

 

This is clipped content from my C# Book. 

You can’t construct an object without using a constructor of some sort. If you define your own constructor, C# takes its constructor away. You can combine these two actions to create a class that can only be instantiated locally.

For example, only methods that are defined within the same assembly as BankAccount can create a BankAccount object with the constructor declared internal, as in the bold text in this chunk of code:

// BankAccount -- Simulate a simple bank account.
public class BankAccount
{
    // Bank accounts start at 1000 and increase sequentially.
    private static int _nextAccountNumber = 1000;
    // Maintain the account number and balance.
    private int _accountNumber;
    double _balance;
    internal BankAccount() // Here’s the internal, not public, constructor.
    {
        _accountNumber = ++_nextAccountNumber; 
        _balance = 0;
    } 

    public string GetString()
    {
        return String.Format("#{0} = {1:N}", _accountNumber, _balance);
    }
}

Comments (1) -

  • mgroves
    Why would you do this?
Comments are closed
Mastodon