Duck Typing in CSharp
List Initializer
Any type implemented IEnumerable
and has a Add(T item): void
method can use list initializer syntax.
Add(T item): void
can be implemented as extension methodICollection
is more generally used to have list initializer enabled, because it's an extension ofIEnumerable
withAdd
method.
cs
_ = new FooCollection<int>() { 1, 2, 3 };
class FooCollection<T> : IEnumerable<T> {
public void Add(T item) { Console.WriteLine(item); }
public IEnumerator<T> GetEnumerator() {
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
// or implement it as extension method
static class Ext {
public static void Add<T>(this FooCollection<T> self, T item) { }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Deconstruction
cs
var (a, b) = new Foo();
class Foo { };
static class FooExtension {
public static void Deconstruct(this Foo self, out int a, out int b) { a = b = 1; }
}
1
2
3
4
5
6
7
2
3
4
5
6
7
Iteration
Any type with a GetEnumerator
implementation can be iterated by foreach
statement.
- can be implemented as an extension method
cs
using System.Collections;
foreach (var _ in new FooIterable()) { }
class FooIterable { };
static class FooExtension {
public static IEnumerator GetEnumerator(this FooIterable _) {
for (int i = 0; i < 100; i++)
yield return i;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12