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 ?

Answers


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
    // ...
  }
} 

Hide it under IEnumerable. You'll get "readonly" collection outise the class and work with List inside:

public class RegistrationManager
{
  public IEnumerable<object> RegisteredObjects
  {
    get
    {
      return _registeredObjects;
    }
  }
  private List<object> _registeredObjects;

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

More protected variant with IReadOnlyColection:

public class RegistrationManager
{
    public IReadOnlyCollection<object> RegisteredObjects
    {
        get { return new ReadOnlyCollection<object>(_registeredObjects); }
    }
    private List<object> _registeredObjects;

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

Need Your Help

Is it ok to erase from stl:map in concurrent with find

c++ stl

I wonder if is it ok to erase from stl:map in concurrent with find?

Algorithm to blend gradient filled corners in image

algorithm image graphics image-processing gradient

I need to put an alpha blended gradient border around an image. My problem is in blending the corners so they are smooth where the horizontal and vertical gradients meet. I believe there is a stan...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.