IDE0220 on foreach (Match m in regex.Matches) – Should Not Occur
See original GitHub issueUsing the following code snippet results in Roslyn analyzer adding an informational warning to the list of analysis results:
foreach (Match m in regex.Matches(text))
{
...
}
IDE0220 'foreach' statement implicitly converts 'object' into 'System.Text.RegularExpressions.Match'. Add an explicit cast to indicate your intention as it may fail at runtime.
MatchCollection.Item[]
, however, doesn’t return object
. It returns a Match
.
Version Used
.NET 6
Steps to Reproduce
- Create a regular expression object.
- Run the
Regex.Matches()
method on that regular expression and feed immediately to aMatch
variable in aforeach
loop.
Expected Behavior
This should be analyzed by the Roslyn analyzer without flaw.
Actual Behavior
The Roslyn analyzer adds an information to the analysis result (roughly translated by me from German to English):
IDE0220 'foreach' statement implicitly converts 'object' into 'System.Text.RegularExpressions.Match'. Add an explicit cast to indicate your intention as it may fail at runtime.
Issue Analytics
- State:
- Created a year ago
- Reactions:4
- Comments:6 (3 by maintainers)
Top Results From Across the Web
Regex.Matches Fails To Find Multiple Matches [duplicate]
The problem is, it returns one match and not 4. Why are the in-between patterns ignored? Do you know what I am missing?...
Read more >Regex.Matches Method (System.Text.RegularExpressions)
Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.
Read more >c# - Regex to first match, then replace found matches
For each word, to find out if a string I am given has any matches. If it does, I perform some (slightly costly)...
Read more >Assign each RegEx Match to Data Row - Help
The issue I am having is only the first match from each pdf document is being assigned to a row within the data...
Read more >When I use foreach for regex.matches, var thinks its type is ...
When you cast to IEnumerable<Match> first, then it bind to the explicit interface method. foreach(var m in (IEnumerable<Match>)matches) ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This still applies to .NET 7.0.
That looks like #60120 rather than #60210. MatchCollection defines
with Enumerator having
Naively, I’d expect both
foreach
and the rule to find the strongly typed path but perhaps that’s not what happens.