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
9/14/2010 6:38:46 AM #

Why would you do this?

Comments are closed

Bill Sempf

Husband. Father. Pentester. Secure software composer. Brewer. Lockpicker. Ninja. Insurrectionist. Lumberjack. All words that have been used to describe me recently. I help people write more secure software.

PageList

profile for Bill Sempf on Stack Exchange, a network of free, community-driven Q&A sites

MonthList