@@ -48,6 +48,12 @@ public static object DuckCast(this object instance, Type targetType)
48
48
[ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
49
49
public static bool TryDuckCast < T > ( this object ? instance , [ NotNullWhen ( true ) ] out T ? value )
50
50
{
51
+ if ( instance is T tInst )
52
+ {
53
+ value = tInst ;
54
+ return true ;
55
+ }
56
+
51
57
if ( instance is not null &&
52
58
DuckType . CreateCache < T > . GetProxy ( instance . GetType ( ) ) is { Success : true } proxyResult )
53
59
{
@@ -71,11 +77,20 @@ public static bool TryDuckCast(this object? instance, Type targetType, [NotNullW
71
77
{
72
78
if ( targetType is null ) { ThrowHelper . ThrowArgumentNullException ( nameof ( targetType ) ) ; }
73
79
74
- if ( instance is not null &&
75
- DuckType . GetOrCreateProxyType ( targetType , instance . GetType ( ) ) is { Success : true } proxyResult )
80
+ if ( instance is not null )
76
81
{
77
- value = proxyResult . CreateInstance ( instance ) ;
78
- return true ;
82
+ var instanceType = instance . GetType ( ) ;
83
+ if ( instanceType == targetType )
84
+ {
85
+ value = instance ;
86
+ return true ;
87
+ }
88
+
89
+ if ( DuckType . GetOrCreateProxyType ( targetType , instanceType ) is { Success : true } proxyResult )
90
+ {
91
+ value = proxyResult . CreateInstance ( instance ) ;
92
+ return true ;
93
+ }
79
94
}
80
95
81
96
value = default ;
@@ -92,6 +107,11 @@ public static bool TryDuckCast(this object? instance, Type targetType, [NotNullW
92
107
public static T ? DuckAs < T > ( this object ? instance )
93
108
where T : class
94
109
{
110
+ if ( instance is T tInst )
111
+ {
112
+ return tInst ;
113
+ }
114
+
95
115
if ( instance is not null &&
96
116
DuckType . CreateCache < T > . GetProxy ( instance . GetType ( ) ) is { Success : true } proxyResult )
97
117
{
@@ -112,10 +132,18 @@ public static bool TryDuckCast(this object? instance, Type targetType, [NotNullW
112
132
{
113
133
if ( targetType is null ) { ThrowHelper . ThrowArgumentNullException ( nameof ( targetType ) ) ; }
114
134
115
- if ( instance is not null &&
116
- DuckType . GetOrCreateProxyType ( targetType , instance . GetType ( ) ) is { Success : true } proxyResult )
135
+ if ( instance is not null )
117
136
{
118
- return proxyResult . CreateInstance ( instance ) ;
137
+ var instanceType = instance . GetType ( ) ;
138
+ if ( instanceType == targetType )
139
+ {
140
+ return instance ;
141
+ }
142
+
143
+ if ( DuckType . GetOrCreateProxyType ( targetType , instanceType ) is { Success : true } proxyResult )
144
+ {
145
+ return proxyResult . CreateInstance ( instance ) ;
146
+ }
119
147
}
120
148
121
149
return null ;
0 commit comments