Reputation:
I dont understand why var m does not return Match. I havent checked but it seems to be returning an object.
foreach (var m in Regex.Matches("dummy text", "(mm)"))
var sz = m.Groups[1]; // error CS1061: 'object' does not contain a definition for 'Groups' and no extension method 'Groups' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
foreach (Match m in Regex.Matches("dummy text", "(mm)"))
var sz = m.Groups[1]; //ok
Upvotes: 3
Views: 165
Reputation: 650
MatchCollection
implements IEnumerable
rather than IEnumerable<Match>
hence the compiler can only infer the type of the variable as object
rather than Match
.
Upvotes: 9
Reputation: 23770
Regex.Matches
returns MatchCollection
that implements IEnumerable
and not IEnumerable<Match>
.
Therefore the default item type is object. When using item type Match
in the foreach you get the expected item type.
Upvotes: 11
Reputation: 421978
var
infers the type of the variable at compile time from the type of the expression it's initialized to. Matches
returns MatchCollection
which implements the old school IEnumerable
and not the generic IEnumerable<Match>
. The type of the Current
property returned by the enumerator returned from IEnumerable.GetEnumerator()
is object
. Thus, var
will infer the type of m
to be object
and not Match
.
When you explicitly specify the type in a foreach
statement and the return type of the enumerator differs, the compiler will silently insert a cast instruction to make that work. No other compile time check can be performed in that case and it will throw an InvalidCastException
at run time in case it fails.
Upvotes: 7