Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add items to ReadOnlyCollection<T> internally (within the same assembly)?

I have the following class:

public class Foo
{
     public List<Bar> Bars {get; internal set;}
}

Now I want to make Bars a ReadOnlyCollection so that the contents of Bars can't be changed publicly:

public class Foo
{
     public ReadOnlyCollection<Bar> Bars {get; internal set;}
}

Now if I have a class within the same assembly that needs to add items to Bars, what is the best way to do this?

This is how I am doing it now:

public class FooHelper
{
   public FooHelper()
   {
      Foo foo = new Foo();
      //Code to modify the collection
      List<Bar> bars = foo.Bars.ToList<Bar>();
      bars.Add(new Bar("BAR BAR BAR"));
      foo.Bars = bars.AsReadOnly();
   }
}

I realized that it would be easier if I have a Private List<Bar> in Foo like so:

public class Foo
{
     private List<Bar> _bars;
     public ReadOnlyCollection<Bar> Bars {get { return _bars.AsReadOnly; }}         
}

... but with this approach, how would I add an item to _bars?

Should I make it Internal, make it an Internal Property, or add a new Internal AddBar() method?

like image 514
Ian Avatar asked Dec 16 '22 14:12

Ian


1 Answers

Personally I would go for adding an internal AddBar method, like so:

public class Foo
{
     private List<Bar> _bars;

     public ReadOnlyCollection<Bar> Bars {get { return _bars.AsReadOnly; }}         

     internal void AddBar(Bar bar)
     {
          _bars.Add(bar);
     }
}

other assemblies will see the readonly collection, making it immutable. Code within the same assembly will only be able to add Bar items, giving you a 'defensive' API.

like image 196
ColinE Avatar answered Jan 20 '23 11:01

ColinE