/
Cast.cs
59 lines (51 loc) · 1.65 KB
/
Cast.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
namespace System.Linq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
return OfTypeIterator<TResult>(source);
}
private static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source)
{
foreach (object? obj in source)
{
if (obj is TResult result)
{
yield return result;
}
}
}
public static IEnumerable<
#nullable disable // there's no way to annotate the connection of the nullability of TResult to that of the source
TResult
#nullable restore
> Cast<TResult>(this IEnumerable source)
{
if (source is IEnumerable<TResult> typedSource)
{
return typedSource;
}
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
return CastIterator<TResult>(source);
}
private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
foreach (object obj in source)
{
yield return (TResult)obj;
}
}
}
}