Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 711
Nicolas Voron Avatar asked Aug 14 '15 13:08

Nicolas Voron


People also ask

Why does adding a new value to list <> overwrite previous values in the list <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!

How to access elements in a list in c#?

C# List access elements. Elements of a list can be accessed using the index notation [] . The index is zero-based.

What is list t in c#?

C# - List<T> The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.Collections.Generic namespace.

How to retrieve data from a list in c#?

Add(new string[] { "Id", "Name", "Age" }); for(int i=0; i<list. Count; i++) for(int j=0; j<list[i]. Count(); j++) Console. WriteLine(list[i][j]); // simpler with foreach foreach(var l in list) foreach(string s in l) Console.


1 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
    // ...
  }
} 
like image 157
Artiom Avatar answered Oct 16 '22 00:10

Artiom