Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, can a method return List such that clients can only read it, but not write to it?

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?

like image 887
zumalifeguard Avatar asked Oct 21 '09 04:10

zumalifeguard


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

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.


2 Answers

Yes, in GetBarList() return _barList.AsReadOnly().

Edit:
As Michael pointed out below, your method would have to return an IList<Bar>.

like image 173
Jay Riggs Avatar answered Oct 13 '22 10:10

Jay Riggs


You may try to use ReadOnlyCollection. Or return just IEnumerable from your method, clients will not have methods to modify it.

like image 32
elder_george Avatar answered Oct 13 '22 10:10

elder_george