You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: source/lectures/data/CList_as_ICollection.md
+20-4Lines changed: 20 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,16 +5,32 @@ tags:
5
5
6
6
# List as ICollection
7
7
8
-
Another way of implementing lists is to make our class realize the [ICollection interface](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1?view=net-9.0):
8
+
## Motivation
9
9
10
+
Another way of implementing lists is to make our class realize the [ICollection interface](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1?view=net-9.0).
10
11
11
-
!include diag/cla/ICollection.md
12
+
Quoting [C# 12 in a Nutshell](https://www.albahari.com/nutshell/):
13
+
14
+
> `ICollection<T>` is the standard interface for countable collections of objects. It provides the ability to determine the size of a collection (`Count`), determine whether an item exists in the collection (`Contains`), copy the collection into an array (`ToArray`), and determine whether the collection is read-only (`IsReadOnly`).
15
+
16
+
Its UML diagram is as follows:
12
17
13
-
This requires implementing a series of properties and methods:
18
+
!include diag/cla/ICollection.md
14
19
20
+
Providing a way of constructing a `IEnumerator<T>` object let C# iterate over our custom lists using `foreach`, so that we can for example write
!include`snippetStart="/* Done with Cell.*/", snippetEnd="/* We are done realizing the ICollection class. */"` code/projects/CList_ICollection/CList_ICollection/CList.cs
23
+
!include`snippetStart="// is that we can iterate over elements of lists now:", snippetEnd="// Done with first example."` code/projects/CList_ICollection/CList_ICollection/Program.cs
18
24
```
19
25
26
+
for `myList1` a `CList<int>` object.
27
+
28
+
Implementing interfaces is an excellent way of signaling to C# that our class respects certain convention on one hand, and to help programmer follow usual guidelines on the other.
20
29
30
+
## Implementation
31
+
32
+
In addition to signaling that our class realizes the interface, using `public class CList<T> : ICollection<T>`, we need to implement the following properties and methods:
!include`snippetStart="/* Done with Cell.*/", snippetEnd="/* We are done realizing the ICollection class. */"` code/projects/CList_ICollection/CList_ICollection/CList.cs
0 commit comments