Skip to content

When I use foreach for regex.matches, var thinks its type is object. Why? #74919

Answered by gfoidl
zms9110750 asked this question in Q&A
Discussion options

You must be logged in to vote

It's because of

public IEnumerator GetEnumerator() => new Enumerator(this);
IEnumerator<Match> IEnumerable<Match>.GetEnumerator() => new Enumerator(this);
and that C# binds to the instance method.
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 var...

I guess this is for historic reasons, as MatchCollection dates back to a time where generics weren't available.

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by teo-tsirpanis
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@stephentoub
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants