The var var and type. Why does var not work here?

I do not understand why var m does not return Match. I havent checked, but it seems to return 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
+3
source share
3 answers

MatchCollectionimplements IEnumerable, but not IEnumerable<Match>, therefore, the compiler can infer the type of the variable as object, rather than Match.

+9
source

Regex.Matchesreturns MatchCollectionwhich implements IEnumerable, not IEnumerable<Match>.

Therefore, the default element type is an object. When using an element type Matchin foreach, you get the expected element type.

+11
source

var , . Matches MatchCollection, IEnumerable, IEnumerable<Match>. Current, , IEnumerable.GetEnumerator(), object. , var m object, Match.

foreach, , cast, . , InvalidCastException .

+7

Source: https://habr.com/ru/post/1723318/


All Articles