|
2 | 2 | // The .NET Foundation licenses this file to you under the MIT license. |
3 | 3 | // See the LICENSE file in the project root for more information. |
4 | 4 |
|
5 | | -using System; |
6 | 5 | using System.Diagnostics.CodeAnalysis; |
7 | 6 | using System.Diagnostics.Contracts; |
8 | 7 | using System.Reflection; |
@@ -41,28 +40,21 @@ public static class TaskExtensions |
41 | 40 | #endif |
42 | 41 | ) |
43 | 42 | { |
44 | | - Type taskType = task.GetType(); |
45 | | - |
46 | | - // Check if the task is actually some Task<T> |
47 | | - if ( |
48 | | -#if NETSTANDARD1_4 |
49 | | - taskType.GetTypeInfo().IsGenericType && |
50 | | -#else |
51 | | - taskType.IsGenericType && |
52 | | -#endif |
53 | | - taskType.GetGenericTypeDefinition() == typeof(Task<>)) |
54 | | - { |
55 | | - // Get the Task<T>.Result property |
56 | | - PropertyInfo propertyInfo = |
| 43 | + // Try to get the Task<T>.Result property. This method would've |
| 44 | + // been called anyway after the type checks, but using that to |
| 45 | + // validate the input type saves some additional reflection calls. |
| 46 | + // Furthermore, doing this also makes the method flexible enough to |
| 47 | + // cases whether the input Task<T> is actually an instance of some |
| 48 | + // runtime-specific type that inherits from Task<T>. |
| 49 | + PropertyInfo? propertyInfo = |
57 | 50 | #if NETSTANDARD1_4 |
58 | | - taskType.GetRuntimeProperty(nameof(Task<object>.Result)); |
| 51 | + task.GetType().GetRuntimeProperty(nameof(Task<object>.Result)); |
59 | 52 | #else |
60 | | - taskType.GetProperty(nameof(Task<object>.Result)); |
| 53 | + task.GetType().GetProperty(nameof(Task<object>.Result)); |
61 | 54 | #endif |
62 | 55 |
|
63 | | - // Finally retrieve the result |
64 | | - return propertyInfo!.GetValue(task); |
65 | | - } |
| 56 | + // Return the result, if possible |
| 57 | + return propertyInfo?.GetValue(task); |
66 | 58 | } |
67 | 59 |
|
68 | 60 | return null; |
|
0 commit comments