Let's say I have a C# class:
class Foo
{
private List<Bar> _barList;
List<Bar> GetBarList() { return _barList; }
...
}
A client can call it:
var barList = foo.GetBarList();
barList.Add( ... );
Is there a way to make the Add
method fail because only a read-only version of _barList
is returned?
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.
Yes, in GetBarList()
return _barList.AsReadOnly()
.
Edit:
As Michael pointed out below, your method would have to return an IList<Bar>
.
You may try to use ReadOnlyCollection. Or return just IEnumerable from your method, clients will not have methods to modify it.
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