How to restrict access to nested class member to enclosing class?

Thomas Levesque picture Thomas Levesque · Nov 3, 2009 · Viewed 22.2k times · Source

Is it possible to specify that members of a nested class can be accessed by the enclosing class, but not other classes ?

Here's an illustration of the problem (of course my actual code is a bit more complex...) :

public class Journal
{
    public class JournalEntry
    {
        public JournalEntry(object value)
        {
            this.Timestamp = DateTime.Now;
            this.Value = value;
        }

        public DateTime Timestamp { get; private set; }
        public object Value { get; private set; }
    }

    // ...
}

I would like to prevent client code from creating instances of JournalEntry, but Journal must be able to create them. If I make the constructor public, anyone can create instances... but if I make it private, Journal won't be able to !

Note that the JournalEntry class must be public, because I want to be able to expose existing entries to client code.

Any suggestion would be appreciated !


UPDATE: Thanks everyone for your input, I eventually went for the public IJournalEntry interface, implemented by a private JournalEntry class (despite the last requirement in my question...)

Answer

Ray Burns picture Ray Burns · Nov 3, 2009

Actually there is a complete and simple solution to this problem that doesn't involve modifying the client code or creating an interface.

This solution is actually faster than the interface-based solution for most cases, and easier to code.

public class Journal
{
  private static Func<object, JournalEntry> _newJournalEntry;

  public class JournalEntry
  {
    static JournalEntry()
    {
      _newJournalEntry = value => new JournalEntry(value);
    }
    private JournalEntry(object value)
    {
      ...