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...)
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
A static nested class cannot access non-static members of its outer class because it does not have an implicit reference to an outer object. 4. Non-static members of a normal inner class can access the static members of any static nested class within the same outer class.
A nested class can be declared with any access modifier, namely private, public, protected, internal, protected internal, or private protected.
A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.
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) { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With