Search code examples
c#listreadonly-collection

Public List without Add


public class RegistrationManager
{
  public List<object> RegisteredObjects;

  public bool TryRegisterObject(object o) 
  {
    // ...
    // Add or not to Registered
    // ...
  }
} 

I want that RegisterObjects be accessible from outside of the class, but also that the only way to populate the RegisterObjects list is through TryRegisterObject(object o).

Is this possible ?


Solution

  • I would hide it under ReadonlyCollection. In this case client won't be able to add elements via casting to IList for example. It totaly depends on how secure you want to be (in simplest scenario exposing IEnumerable will be pretty enough).

    public class RegistrationManager
    {
      private List<object> _registeredObjects;
      ReadOnlyCollection<object> _readOnlyRegisteredObjects;
    
      public RegistrationManager()
      {
          _registeredObjects=new List<object>();
          _readOnlyRegisteredObjects=new ReadOnlyCollection<object>(_registeredObjects);
      }
    
      public IEnumerable<object> RegisteredObjects
      {
         get { return _readOnlyRegisteredObjects; }
      }
    
    
      public bool TryRegisterObject(object o) 
      {
        // ...
        // Add or not to Registered
        // ...
      }
    }