When I use foreach for regex.matches, var thinks its type is object. Why? #74919
-
It can even use generic LINQ |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
It's because of When you cast to IEnumerable<Match> first, then it bind to the explicit interface method.
foreach(var m in (IEnumerable<Match>)matches)
{
// m is of type Match
} Or if you use the explicit type instead of I guess this is for historic reasons, as |
Beta Was this translation helpful? Give feedback.
-
As @gfoidl mentioned, However, LINQ should pick up the explicit generic implementation as long as you're on a modern version of .NET. If you're still on .NET Framework you should be able to use |
Beta Was this translation helpful? Give feedback.
-
What happens if you delete the old API or change to the generic version of the iterator? How much will this affect the previous code? |
Beta Was this translation helpful? Give feedback.
It's because of
runtime/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/MatchCollection.cs
Lines 71 to 73 in 6294858
When you cast to
IEnumerable<Match>
first, then it bind to the explicit interface method.Or if you use the explicit type instead of
var
...I guess this is for historic reasons, as
MatchCollection
dates back to a time where generics weren't available.