tags:

views:

106

answers:

3

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
+10  A: 

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.

Elisha
You mean "returns" instead of "implements".
Stefan Steinegger
Thank Stefan, I missed the return type in answer :)
Elisha
+7  A: 

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.

Mehrdad Afshari
+6  A: 

MatchCollection implements IEnumerable rather than IEnumerable<Match> hence the compiler can only infer the type of the variable as object rather than Match.

RTPeat
You win for explaining everything i wanted to know when the least amount of words.
acidzombie24
and i feel this answer is complete.
acidzombie24
Thanks, glad I left my short and sweet answer on!
RTPeat