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?
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.
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